Rxjava observeOn and subscribeOn in Retrofit
Basic, we will have
Observable.subscribe(Observer);// => Observer observe Observable and Observable subscribe Observer
Example
requestInterface.callApi().subscribe(new Observer...); // requestInterface.callApi() <=> Observable
From the http://reactivex.io/documentation/operators/subscribeon.html
SubscribeOn
- 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 (affect 2 things)
It instructs the Observable to send notifications to Observers on a specified Scheduler.
ObserveOn affects the thread that the Observable will use below where that operator appears
Example
registerUserReturnedObserverble() // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.andThen(loginReturnObserverble()) // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.observeOn(AndroidSchedulers.mainThread())
.andThen(getUserDataReturnObserverble()) // run on main thread because .observeOn(AndroidSchedulers.mainThread()) is above this operator (line 3)
.subscribeOn(Schedulers.io())
.subscribe(new Observer<Void>{
// run on main thread because observeOn(AndroidSchedulers.mainThread())
});