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

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.
主站蜘蛛池模板: 剑川县| 浮山县| 稻城县| 新营市| 青海省| 章丘市| 离岛区| 巫山县| 大渡口区| 临海市| 新龙县| 盐山县| 武夷山市| 寿阳县| 荔波县| 永年县| 寻乌县| 科技| 德惠市| 綦江县| 西乌珠穆沁旗| 吉木乃县| 田东县| 惠水县| 西畴县| 长顺县| 内江市| 绥德县| 张家界市| 盐亭县| 靖边县| 清新县| 上蔡县| 北流市| 广宁县| 巴里| 讷河市| 卓资县| 临猗县| 崇礼县| 蒲城县|