RxJava 1和2对于Completable.andThen()具有不同的结果

时间:2019-06-12 21:11:59

标签: rx-java rx-java2

我创建了以下课程来演示问题:

public class TestRx {

    public void run() {
        // RxJava2
        new CompositeDisposable().add(completableRxJava2()
                .subscribeOn(io.reactivex.schedulers.Schedulers.computation())
                .andThen(testSingleRxJava2())
                .observeOn(io.reactivex.schedulers.Schedulers.newThread())
                .subscribe(
                        this::success,
                        Throwable::printStackTrace));

        // RxJava1
        new CompositeSubscription().add(completableRxJava1()
                .subscribeOn(Schedulers.io())
                .andThen(testSingleRxJava1())
                .observeOn(Schedulers.computation())
                .subscribe(
                        this::success,
                        Throwable::printStackTrace));
    }

    private io.reactivex.Completable completableRxJava2() {
        return io.reactivex.Completable.fromAction(() ->
                System.out.println("completableRxJava2 " + Thread.currentThread().getName()));
    }

    private io.reactivex.Single<String> testSingleRxJava2() {
        return io.reactivex.Single.fromCallable(() -> {
            System.out.println("testSingleRxJava2 " + Thread.currentThread().getName());
            return "END";
        });
    }

    private Completable completableRxJava1() {
        return Completable.fromAction(() ->
                System.out.println("completableRxJava1 " + Thread.currentThread().getName()));
    }

    private Single<String> testSingleRxJava1() {
        return Single.fromCallable(() -> {
            System.out.println("testSingleRxJava1 " + Thread.currentThread().getName());
            return "END";
        });
    }

    private void success(final String s) {
        System.out.println(s);
        System.out.println();
    }
}

当我执行run()方法时,这是输出:

completableRxJava2 RxComputationThreadPool-1
testSingleRxJava2 RxComputationThreadPool-1
END

completableRxJava1 RxIoScheduler-2

我对结果不了解。

  1. 为什么未在testSingleRxJava2上执行RxNewThreadScheduler
  2. 为什么RxJava1不执行testSingleRxJava1方法?

有时输出会更加混乱,返回的结果仅仅是这样:

completableRxJava2 RxComputationThreadPool-1
testSingleRxJava2 RxComputationThreadPool-1
END

没有RxJava1的输出。

为什么会这样?

RxJava1版本:1.3.8 RxJava2版本:2.2.9

1 个答案:

答案 0 :(得分:2)

  
      
  1. 为什么不在RxNewThreadScheduler上执行testSingleRxJava2?
  2.   

observeOn影响下游操作,因此,如果希望testSingleRxJava2在新线程上执行,则应将代码更改为:

    .observeOn(io.reactivex.schedulers.Schedulers.newThread())
    .andThen(testSingleRxJava2())
  
      
  1. 为什么RxJava1不执行testSingleRxJava1方法?
  2.   

这可能是因为在运行该代码时,主线程在io线程有机会打印之前就已经完成了,请尝试在运行方法的末尾添加Thread.sleep(1000),它应该始终打印< / p>