当前位置:   article > 正文

RxJava操作符 ~ defer_rxjava defer

rxjava defer

在这里插入图片描述
RxJava的 defer 操作符作以确保Observable代码在被订阅后才执行,而不是创建后立即执行

@Test
    public void defer() {

        Disposable disposable = Observable.defer(new Callable<ObservableSource<?>>() {
            @Override
            public ObservableSource<?> call() throws Exception {
                return getRxJavaCreateExampleData();
            }
        })

                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        System.out.println("rxJavaDeferExample:" + Thread.currentThread().getName() + " consumer --> " + o.toString());
                    }
                });
    }


    public Observable<Integer> getRxJavaCreateExampleData() {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) {
                System.out.println("getRxJavaCreateExampleData:" + Thread.currentThread().getName() + " --> " + 1);
                emitter.onNext(1);

                System.out.println("getRxJavaCreateExampleData:" + Thread.currentThread().getName() + " --> " + 2);
                emitter.onNext(2);

                System.out.println("getRxJavaCreateExampleData:" + Thread.currentThread().getName() + " --> " + 3);
                emitter.onNext(3);
                emitter.onComplete();

                System.out.println("getRxJavaCreateExampleData:" + Thread.currentThread().getName() + " --> " + 4);
                emitter.onNext(4);

            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/177355
推荐阅读
相关标签
  

闽ICP备14008679号