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

Observer – an iterator's dual

Clojure's sequence operators, such as map, filter, reduce, and so on, support Java iterables. As the name implies, an iterable is an object that can be iterated over. At a low level, this is supported by retrieving an Iterator reference from such an object. Java's iterator interface looks like the following:

public interface Iterator<E> { 
    boolean hasNext(); 
    E next(); 
    void remove(); 
} 

When passed an object that implements this interface, Clojure's sequence operators pull data from it by using the next method, while using the hasNext method to know when to stop.

The remove method is required to remove its last element from the underlying collection. This in-place mutation is clearly unsafe in a multithreaded environment. Whenever Clojure implements this interface for the purposes of interoperability, the remove method simply throws UnsupportedOperationException.

An observable, on the other hand, has observers subscribed to it. Observers have the following interface:

public interface Observer<T> { 
    void onCompleted(); 
    void onError(Throwable e); 
    void onNext(T t); 
} 

As we can see, an observer implementing this interface will have its onNext method called with the next value available from whatever observable it's subscribed to, hence it being a push-based notification model.

This duality[1] becomes clearer if we look at both interfaces side by side:

Iterator<E> {                       Observer<T> { 
    boolean hasNext();                  void onCompleted(); 
    E next();                           void onError(Throwable e); 
    void remove();                      void onNext(T t); 
}                                       } 

Observables provide the ability to have producers push items asynchronously to consumers. A few examples will help solidify our understanding.

主站蜘蛛池模板: 尼木县| 南和县| 赤壁市| 友谊县| 通许县| 信宜市| 汉源县| 象州县| 祥云县| 监利县| 永康市| 上高县| 延寿县| 闸北区| 双柏县| 津市市| 滨州市| 彰化县| 黄山市| 开远市| 镇江市| 黑水县| 黄浦区| 长葛市| 剑阁县| 锦州市| 济阳县| 安乡县| 临沂市| 兴山县| 鱼台县| 留坝县| 潞城市| 澄城县| 唐海县| 宝应县| 镶黄旗| 罗田县| 昭通市| 班戈县| 固安县|