subscribeOn

The .subscribeOn() modifies the Scheduler (thread) where the source Observable is supposed to emit items. Basically, it modifies the thread where all the data handling starts.

Let's say that we've created an Observable with Observable.just(), and we subscribe to it. The subscription flow looks like the one specified in the following figure (let's use it as a baseline):

If .subscribeOn() is called, it will change the execution thread for the entire chain, as in the following figure:

It is also useful to note that multiple calls to .subscribeOn() and the place where they are put will have the same effect on the source Observable, and only the first call to .subscribeOn() will have effect, as it changes only the Scheduler on which the Observable starts operating.

Consider the following example:

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

It will produce the following output:

doOnNext:RxSingleScheduler-1:One
doOnNext:RxSingleScheduler-1:One
subscribe:RxSingleScheduler-1:One
doOnNext:RxSingleScheduler-1:Two
doOnNext:RxSingleScheduler-1:Two
subscribe:RxSingleScheduler-1:Two
doOnNext:RxSingleScheduler-1:Three
doOnNext:RxSingleScheduler-1:Three
subscribe:RxSingleScheduler-1:Three

As we can see, there are no mentions of the IO Scheduler or a NewThread Scheduler being used--only the Single Scheduler was applied.

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

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