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

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.
主站蜘蛛池模板: 丰顺县| 中牟县| 南皮县| 济南市| 临泽县| 怀远县| 武冈市| 丘北县| 基隆市| 孙吴县| 葫芦岛市| 临泉县| 前郭尔| 巴楚县| 丰都县| 婺源县| 长海县| 台中市| 华蓥市| 新建县| SHOW| 清涧县| 宝兴县| 威海市| 成安县| 色达县| 仙居县| 东阳市| 宁强县| 松溪县| 白河县| 北票市| 古丈县| 万宁市| 鄯善县| 金寨县| 宿州市| 晋宁县| 日土县| 阜平县| 唐山市|