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

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.
主站蜘蛛池模板: 上蔡县| 新河县| 海阳市| 仙居县| 葫芦岛市| 五常市| 龙川县| 图木舒克市| 三穗县| 义乌市| 吉首市| 德州市| 鲜城| 苏尼特左旗| 响水县| 鄂托克旗| 海丰县| 清苑县| 樟树市| 铜鼓县| 安仁县| 东乌珠穆沁旗| 象州县| 历史| 湄潭县| 社旗县| 内江市| 兴山县| 虎林市| 礼泉县| 彰武县| 赤水市| 湛江市| 公安县| 平度市| 德兴市| 潮安县| 桐城市| 阿坝县| 奇台县| 新源县|