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
observeOn() simply changes the thread of all operators further Downstream. People usually have this misconception that observeOn also acts as upstream, but it doesn't. subscribeOn() only influences the thread which is going to be used when Observable is going to get subscribed to and it will stay on it downstream.
It changes the thread as many times as you write it. flatMap starts the chain only during root chain data emission. No actions are performed during the root stream subscription process. Operators interval/delay/timer subscribe to computation under the hood, by default.
subscribeOn() operator tells the source Observable which thread to emit and push items on all the way down to Observer (hence, it affects both upstream and downstream operators). It does not matter where you put the subscribeOn() in your Observable chain of operators.
FlatMap transforms the items emitted by an Observable into Observables. FlatMap Operator. So, the main difference between Map and FlatMap is that FlatMap mapper returns an observable itself, so it is used to map over asynchronous operations. Very important: FlatMap is used to map over asynchronous operations.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With