官术网_书友最值得收藏!

Operators

Now the principles of observables and observers should start to be more clear. However, you may wonder: how can this make development of asynchronous code easier? After all, what was described in the previous section is almost exactly the description of the observer design pattern, with additions for the management of completion and errors. The answer is that this is not the whole story, but the foundation of an extensible framework. What made ReactiveX different from other frameworks is its inspiration from functional programming, with the availability of many operators that can be chained in a pipeline. In the RxPY implementation, operators are methods of the Observable class. On some implementations of ReactiveX, they are implemented as functions which allow us to add new operators very easily. Look at the following example of pseudo-code:

Observable.from_(...)
.filter()
.distinct()
.take(20)
.map(...)

This is what a ReactiveX code looks like. It is a succession of operators that modify the items flowing through them. An operator can be seen as a monad: a construction that encapsulates program logic instead of data. (I apologize to functional programmers for this very simplistic definition.) An operator takes an observable as input and returns another observable. So, we can consider the observable data type as an abstract type that is used to compose functions together. Some operators accept other input parameters to provide additional program logic that will be executed on each item received on the operator. For example, the map operator that will be used later takes a function as a parameter. This function contains the code logic that will be executed on each item sent on the input observable.

Operators are not limited to the code logic of items. Since they work on the observable data type, they can also be used to manage observables' completion and errors. For example, some operators use completion events to chain observables one after another. Other operators use error events to gracefully manage these errors.

The RxPY implementation contains about 140 operators. We will cover the most used, which is about half of them. As you will be writing RxPY code, you will also be writing your own operators, even if they will not be directly usable in the kind of pipeline that we saw earlier. As we will see, writing a custom operator is the way to factorize code and make functions simpler when using ReactiveX.

主站蜘蛛池模板: 白朗县| 深圳市| 沈阳市| 石楼县| 务川| 麻城市| 双江| 孝感市| 邵东县| 和硕县| 伊春市| 荆州市| 蒲江县| 太原市| 德庆县| 武山县| 邵武市| 塔河县| 逊克县| 乐平市| 虹口区| 海安县| 恭城| 抚宁县| 新绛县| 商都县| 富阳市| 鞍山市| 施甸县| 绥阳县| 菏泽市| 乌兰浩特市| 城口县| 荆州市| 新宾| 武定县| 团风县| 五台县| 常德市| 娄烦县| 齐河县|