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

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.

主站蜘蛛池模板: 辉南县| 宿松县| 盐源县| 新野县| 阿勒泰市| 白城市| 襄樊市| 萨迦县| 盐城市| 湘乡市| 武威市| 建平县| 兖州市| 信宜市| 凯里市| 许昌市| 团风县| 江陵县| 北碚区| 洛隆县| 恭城| 泾阳县| 井陉县| 岐山县| 上高县| 洛扎县| 遂昌县| 汉阴县| 湖州市| 民丰县| 龙山县| 内丘县| 盐边县| 三都| 鄱阳县| 凤山县| 贵溪市| 罗城| 穆棱市| 来宾市| 铜山县|