Refer:
custom-rxjs-operators-by-example
rxjs-custom-operator-internal-variables
operators-defer
pipeable-operators
operator-creation
Two ways to create Custom Pipe:
一是从0开始自定义Operator
;二是利用现有的Operator
;
GuideLine:
In the most common case, users might like to create an operator to be used only by their app. These can be developed in any way the developer sees fit, but here are some guidelines:
Operators
should always return anObservable
. You're performing operations on unknown sets of things to create new sets. It only makes sense to return a new set. If you create a method that returns something other than anObservable
, it's not an operator, and that's fine.
Operators
返回类型是Observable
Be sure to manage subscriptions created inside of the
Observable
your operator returns. Your operator is going to have tosubscribe
to the source (or this) inside of the returnedObservable
, be sure that it's returned as part ofunsubscribe
handler orsubscription
.Be sure to handle exceptions from passed functions. If you're implementing an
Operator
that takes a function as an argument, when you call it, you'll want to wrap it in atry/catch
and send the error down theerror()
path on theobservable
.
如果自定义的Operator
需要take一个函数作为参数,需要注意函数的异常处理。需要将函数的调用用try/catch
包裹,并且将error推送到observable
的error()
。Be sure to teardown scarce resources in your
unsubscribe
handler of your returnedObservable
. If you're setting up event handlers or a web socket, or something like that, theunsubscribe
handler is a great place to remove that event handler or close that socket.
确保在unsubscribe
种进行资源释放。如果是事件处理程序或web套接字,unsubscribe
时需要删除该事件处理程序或关闭该套接字。