RxJava multiple subscribeOn() in chain
Asked Answered
W

1

9

I'd like to know what happens when we have multiple subscribeOn() methods in a RxJava chain. For instance if I had a chain that was something like this,

    Single.fromCallable { repository.apiCall1() }
        .subscribeOn(Schedulers.io())
        .flatMap { result -> Single.fromCallable { repository.apiCall2() } }
        .subscribeOn(Schedulers.io())
        .map { // do something }
        .observeOn(Schedulers.ui())

would this mean that the thread the API calls run on is not the same? And what would be the impact / effect of removing the first subscribeOn(Schedulers.io()) call in this chain above?

Appreciate any insights on this

Wholly answered 29/6, 2019 at 9:16 Comment(0)
A
5

It looks it wont have any effect. It doesn´t matter where you put the subscribeOn in the chain that will have the same effect.

As per documentation, observeOn has a different behaviour, so you can change the thread where you´re observing the result at any point in the chain.

From the Rx documentation:

the SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use below where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate.

http://reactivex.io/documentation/operators/subscribeon.html

Arsenault answered 29/6, 2019 at 9:25 Comment(2)
hmm.. what does that mean for the other subscribeOn() calls? (would they just create another thread un-necessarily for nothing). Is there some way to test only one thread is actually being created / used?Wholly
It will use the thread of the first subscribeOn of the chaining call. You can check an example in this article (subscribeOn() gotchas section): proandroiddev.com/…Arsenault

© 2022 - 2024 — McMap. All rights reserved.