observeOn

.observeOn() works a bit differently than .subscribeOn(). Whenever .observeOn() is called, it changes the thread of downstream where the code is getting executed.

Consider that we have a flow that looks like this:

Observable.just("One", "Two", "Three")
.doOnNext(i -> log("doOnNext", i))
.observeOn(Schedulers.newThread())
.doOnNext(i -> log("doOnNext", i))
.subscribe(i -> log("subscribe", i));

Its structure can be represented in the following figure:

The output of such a call will be as follows:

doOnNext:main:One
doOnNext:main:Two
doOnNext:main:Three
doOnNext:RxNewThreadScheduler-1:One
subscribe:RxNewThreadScheduler-1:One
doOnNext:RxNewThreadScheduler-1:Two
subscribe:RxNewThreadScheduler-1:Two
doOnNext:RxNewThreadScheduler-1:Three
subscribe:RxNewThreadScheduler-1:Three

We can see that the first .doOnNext() block was executed in the main block, but the next one was executed on the NewThread Scheduler.

Consider that we were to change the code by adding one more .observeOn() call before the .subscribe, as follows:

Observable.just("One", "Two", "Three")
.doOnNext(i -> log("doOnNext", i))
.observeOn(Schedulers.newThread())
.doOnNext(i -> log("doOnNext", i))
.observeOn(Schedulers.computation())
.subscribe(i -> log("subscribe", i));

Then, the output would be the following:

doOnNext:main:One
doOnNext:main:Two
doOnNext:main:Three
doOnNext:RxNewThreadScheduler-1:One
doOnNext:RxNewThreadScheduler-1:Two
doOnNext:RxNewThreadScheduler-1:Three
subscribe:RxComputationThreadPool-1:One
subscribe:RxComputationThreadPool-1:Two
subscribe:RxComputationThreadPool-1:Three

It can be seen that the execution thread of the .subscribe() block was changed, while the others were left as they were before.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.255.250