RxJava

RxJava<第三篇>:do操作符

2019-03-12  本文已影响7人  NoBugException

基本代码如下:

    Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) {
            emitter.onNext("hello word A");
            emitter.onNext("hello word B");
            emitter.onNext("hello word C");
            //emitter.onError(new Throwable("this is nullpointException"));
            emitter.onComplete();
        }
    }).doOnSubscribe(new Consumer<Disposable>() {
        @Override
        public void accept(Disposable disposable) throws Exception {
            System.out.println("doOnSubscribe -- 观察者和被观察者连接时被调用");
        }
    }).doOnNext(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            System.out.println("doOnNext -- "+s);
        }
    }).doAfterNext(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            System.out.println("doAfterNext -- "+s);
        }
    }).doOnDispose(new Action() {
        @Override
        public void run() throws Exception {
            System.out.println("doOnDispose -- ");
        }
    }).doAfterTerminate(new Action() {
        @Override
        public void run() throws Exception {
            System.out.println("doAfterTerminate -- ");
        }
    }).doFinally(new Action() {
        @Override
        public void run() throws Exception {
            System.out.println("doFinally -- ");
        }
    }).doOnComplete(new Action() {
        @Override
        public void run() throws Exception {
            System.out.println("doOnComplete -- ");
        }
    }).doOnError(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            System.out.println("doOnError -- ");
        }
    }).doOnLifecycle(new Consumer<Disposable>() {
        @Override
        public void accept(Disposable disposable) throws Exception {
            System.out.println("doOnLifecycle1 -- ");
        }
    }, new Action() {
        @Override
        public void run() throws Exception {
            System.out.println("doOnLifecycle2 -- ");
        }
    }).doOnEach(new Consumer<Notification<String>>() {
        @Override
        public void accept(Notification<String> stringNotification) throws Exception {
            System.out.println("doOnEach -- "+stringNotification.getValue());
        }
    }).subscribe();

执行效果如下:

图片.png

基本说明

(1)doOnSubscribe:在被观察者和观察者产生关联的时候被调用,disposable可以立即取消订阅;
(2)doOnLifecycle:可以在订阅之后设置是否取消订阅;
(3)doNext和doAfterNext:可以接收到被观察者发射过来的数据;
(4)doOnEach:当onNext、onError、onComplete被触发是被调用;
(5)doOnComplete:当触发onComplete时被调用;
(6)doOnError:当触发onError时被调用;
(7)doFinally:当触发onError或onComplete时被调用;
(8)doOnDispose:当取消订阅时被调用;
(9)doAfterTerminate:订阅终止时被调用;

上一篇下一篇

猜你喜欢

热点阅读