响应式编程之doOnEach

74 阅读1分钟

该被观察者存在两种方式,方式1:

public final Observable<T> doOnEach(Observer<? super T> observer) {
    return unsafeCreate(new OnSubscribeDoOnEach<T>(this, observer));
}

方式2:

public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNotification) {
    Observer<T> observer = new ActionNotificationObserver<T>(onNotification);
    return unsafeCreate(new OnSubscribeDoOnEach<T>(this, observer));
}

1、ActionNotificationObserver

public final class ActionNotificationObserver<T> implements Observer<T> {

    final Action1<Notification<? super T>> onNotification;

    public ActionNotificationObserver(Action1<Notification<? super T>> onNotification) {
        this.onNotification = onNotification;
    }

    @Override
    public void onNext(T t) {
        onNotification.call(Notification.createOnNext(t));
    }

    @Override
    public void onError(Throwable e) {
        onNotification.call(Notification.createOnError(e));
    }

    @Override
    public void onCompleted() {
        onNotification.call(Notification.createOnCompleted());
    }
}

在onNext、onCompleted、onError方法调用时,都会回调call方法。由此得知该类被观察者在订阅完成前后各订阅一次。

同样都是OnSubscribeDoOnEach类型的Observable,目前只有该类型的Observable会被调用两次,存在多个OnSubscribeDoOnEach类型的Observable,调用顺序决定于定义顺序。

链式调用过程中以初始化的订阅者之#onNext方法调用为界限,也是调用链式中相关onCompleted|onTerminate等方法的开始。