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

Custom observables

Rx provides many more factory methods to create observables, but it is beyond the scope of this book to cover them all. Interested readers are advised to consult the Rx documentation (see https://github.com/ReactiveX/RxJava/wiki/Creating-Observables) which provides examples of other factory methods.

Nevertheless, sometimes, none of the built-in factories are what you want. For such cases, Rx provides the create method. We can use it to create a custom observable from scratch.

As an example, we'll create our own version of the just observable we used earlier in this chapter:

(defn just-obs [v] 
  (rx/observable* 
   (fn [observer] 
     (rx/on-next observer v) 
     (rx/on-completed observer)))) 
 
(rx/subscribe (just-obs 20) prn) 

First, we create a function, just-obs, which implements our observable by calling the observable* function.

When creating an observable in this way, the function passed to observable* will get called with an observer as soon as one subscribes to us. When this happens, we are free to do whatever computation—and even I/O—we need in order to produce values and push them to the observer.

We should remember to call the observer's onCompleted method whenever we're done producing values. The preceding snippet will print 20 to the REPL.

While creating custom observables is fairly straightforward, we should make sure that we exhaust the built-in factory functions first, only then resorting to creating our own.
主站蜘蛛池模板: 侯马市| 姚安县| 嘉义县| 遂川县| 嘉兴市| 彭州市| 岳普湖县| 沭阳县| 朔州市| 油尖旺区| 五台县| 巨野县| 潍坊市| 吉水县| 蕉岭县| 南丹县| 疏附县| 太康县| 垣曲县| 宜都市| 宁波市| 博爱县| 南宁市| 微山县| 连城县| 平远县| 英德市| 竹北市| 绥阳县| 贡觉县| 白河县| 三门县| 牡丹江市| 密云县| 绥化市| 邻水| 乌兰县| 千阳县| 河南省| 阆中市| 绥芬河市|