RxJava: 2.x: Single.flatMapObservable does not respect observeOn

RxJava version 2.1.2.

The following code:

Single.just("Test")
      .subscribeOn(Schedulers.computation())
      .flatMapObservable(
            s -> {
                System.out.println("1: " + Thread.currentThread());

                return Observable.just(1)
                      .observeOn(Schedulers.io())
                      //.doOnNext(o -> System.out.println("2: " + Thread.currentThread()))
                 ;
            }
      )
      .subscribe(o -> {
          System.out.println("3: " + Thread.currentThread());
      });

…produces the following output:

1: Thread[RxComputationThreadPool-1,5,main]
3: Thread[RxComputationThreadPool-1,5,main]

Expected output here is:

1: Thread[RxComputationThreadPool-1,5,main]
3: Thread[RxCachedThreadScheduler-1,5,main]

However, when the line containing doOnNext is uncommented, this is the output:

1: Thread[RxComputationThreadPool-1,5,main]
2: Thread[RxCachedThreadScheduler-1,5,main]
3: Thread[RxCachedThreadScheduler-1,5,main]

It looks like the thread is not switched in the first case.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 20 (18 by maintainers)

Most upvoted comments

If you bind data, delaying a frame will cause a noticeable UI problem.

Especially on Android, this behavior may lead to crashes if the value is not emitted on the main thread

That’s why peoply, by reflex, apply .observeOn(AndroidSchedulers.mainThread()) to route the results back to the main thread.

The problem with that is you end up delaying frames and breaking sources and emit synchronously. The general recommendation is to push observeOn as far “up” into the streams as possible so the fact that they may not be honored is a bit disturbing.