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

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.

主站蜘蛛池模板: 安塞县| 涞水县| 商水县| 浑源县| 香港| 井陉县| 定兴县| 兴隆县| 晋宁县| 卢湾区| 冀州市| 新乡县| 昌宁县| 滦南县| 中方县| 清新县| 稻城县| 吉林市| 南召县| 灵山县| 延安市| 柏乡县| 迭部县| 都兰县| 灵石县| 肃宁县| 应用必备| 尚志市| 绍兴市| 陆河县| 兴文县| 扶余县| 山西省| 微山县| 奉新县| 锦州市| 凉城县| 丰台区| 禹州市| 霍山县| 东乌|