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

The Observer interface

The onNext(), onComplete(), and onError() methods actually define the Observer type, an abstract interface implemented throughout RxJava to communicate these events. This is the Observer definition in RxJava shown in the code snippet. Do not bother yourself about onSubscribe() for now, as we will cover it at the end of this chapter. Just bring your attention to the other three methods:

    package io.reactivex;

import io.reactivex.disposables.Disposable;

public interface Observer<T> {
void onSubscribe(Disposable d);
void onNext(T value);
void onError(Throwable e);
void onComplete();
}

Observers and source Observables are somewhat relative. In one context, a source Observable is where your Observable chain starts and where emissions originate. In our previous examples, you could say that the Observable returned from our Observable.create() method or Observable.just() is the source Observable. But to the filter() operator, the Observable returned from the map() operator is the source. It has no idea where the emissions are originating from, and it just knows that it is receiving emissions from the operator immediately upstream from it, which come from map().

Conversely, each Observable returned by an operator is internally an Observer that receives, transforms, and relays emissions to the next Observer downstream. It does not know whether the next Observer is another operator or the final Observer at the end of the chain. When we talk about the Observer, we are often talking about the final Observer at the end of the Observable chain that consumes the emissions. But each operator, such as map() and filter(), also implements Observer internally.

We will learn in detail about how operators are built in Chapter 9, Transformers and Custom Operators. For now, we will focus on using an Observer for the subscribe() method.

In RxJava 1.0, the Subscriber essentially became a Observer in RxJava 2.0. There is an Observer type in RxJava 1.0 that defines the three event methods, but the Subscriber is what you passed to the subscribe() method, and it is implemented Observer. In RxJava 2.0, a Subscriber only exists when talking about Flowables, which we will discuss in Chapter 8, Flowables and Backpressure.
主站蜘蛛池模板: 苗栗县| 宁陕县| 唐河县| 新绛县| 长武县| 六枝特区| 自贡市| 株洲市| 宝坻区| 延长县| 杭锦后旗| 裕民县| 汶川县| 辽阳县| 华蓥市| 泽州县| 宁国市| 麻栗坡县| 江山市| 墨脱县| 博野县| 黄石市| 峨眉山市| 铜陵市| 双牌县| 河北省| 青冈县| 柏乡县| 桦川县| 阳高县| 阳城县| 临漳县| 昌黎县| 峨边| 五寨县| 苗栗市| 孝义市| 砚山县| 措勤县| 上蔡县| 奉节县|