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

Zip operator

One more operator that we will look at is zip. This has a more complex behavior, as it combines values from two parallel streams by applying a zip function. It is often used for data enrichment, especially when parts of an expected result are retrieved from different sources, as shown in the following diagram:

Diagram 2.10 Zip o perator: combines the emissions of multiple Observables together via a specified function and emits single items for each combination based on the results of this function

Here, Netflix uses a zip operator to combine movie descriptions, movie posters, and movie ratings when streaming a list of recommended videos. However, for the sake of simplicity, let's zip just two streams of string values, as shown in the following code:

Observable.zip(
Observable.just("A", "B", "C"),
Observable.just("1", "2", "3"),
(x, y) -> x + y
).forEach(System.out::println);

The preceding code joins elements one by one from two streams, as depicted in the preceding diagram, and produces the following console output:

A1
B2
C3

To learn more about operators that are commonly used in reactive programming (not only in RxJava) visit http://rxmarbles.com. This site contains interactive diagrams that reflect actual operator behavior. In turn, the interactive UI allows us to visualize the events' transformation with regards to the order and time in which each event appeared in the streams. Note that the site itself is built with the RxJS library (see https://github.com/ReactiveX/rxjs for more details), which is RxJava's counterpart in the JavaScript world.

As previously mentioned, RxJava's Observable provides dozens of stream transformation operators that confidently cover a lot of use cases. Of course, RxJava does not only limit developers to operators provided by the library. One can also write a custom operator by implementing a class that is derived from the Observable.Transformer<T, R>. Such operator logic could be included in the workflow by applying the Observable.compose(transformer) operator. At the moment, we are not going to dive into the operator's building theory or practice; we are going to cover that in later chapters, partially. So far, it will be enough to highlight that RxJava provides a robust set of instruments for building complicated asynchronous workflows that are mainly limited by our imagination, not by the library.

主站蜘蛛池模板: 神池县| 津市市| 双柏县| 汪清县| 泰州市| 五莲县| 民权县| 吴川市| 大渡口区| 内江市| 德令哈市| 阳新县| 舟曲县| 甘肃省| 马山县| 建瓯市| 八宿县| 博兴县| 大悟县| 涟水县| 永昌县| 云南省| 益阳市| 吴桥县| 和硕县| 新安县| 萨迦县| 临海市| 新田县| 望都县| 海晏县| 永顺县| 海盐县| 河池市| 凌海市| 新竹市| 龙南县| 赞皇县| 易门县| 永泰县| 穆棱市|