Skip to content

Instantly share code, notes, and snippets.

@MyDogTom
Last active February 13, 2018 18:01
Show Gist options
  • Save MyDogTom/ecbf0cb229ddfec4d85b to your computer and use it in GitHub Desktop.
Save MyDogTom/ecbf0cb229ddfec4d85b to your computer and use it in GitHub Desktop.
rxJava observeOn and subscribeOn explanation source: https://github.com/ReactiveX/RxJava/issues/2925#issuecomment-98649659
Observable.just(1) // 1 will be emited in the IO thread pool
.subscribeOn(Schedulers.io())
.flatMap(...) // will be in the IO thread pool
.observeOn(Schedulers.computation())
.flatMap(...) // will be executed in the computation thread pool
.observeOn(AndroidSchedulers.mainThread())
.subscribe(); // will be executed in the Android main thread (if you're running your code on Android)
// "main" represents thread where entire chain is executed. But (!) we are not switching back to main thread
//neverthelesss all "doOnSubscribe" are executed in main thread
// That happens because doOnSubscribe is executed immediately in the thread where entire chain is exected.
// doOnTerminated, doFinaly, doOnNext are deferred, that's why they are affected by observeOn
Observable.just(1) // 1 will be emited in the IO thread pool
.doOnSubscribe(...) // io thread
.doOnNext(...) // io thread
.doOnTerminate(...) // io thread
.doFinally(...) // io thread
.subscribeOn(Schedulers.io())
.flatMap(...) // io thread
.doOnSubscribe(...) // !!! main thread
.doOnNext(...) // io thread
.doOnTerminate(...) // io thread
.doFinally(...) //io thread
.observeOn(Schedulers.computation())
.flatMap(...) // computation thread
.doOnSubscribe(...) // !!! main
.doOnNext(...) // computation thread
.doOnTerminate(...) // computation thread
.doFinally(...) //computation thread
.observeOn(Schedulers.newThread())
.doOnSubscribe(...) // !!! main
.doOnNext(...) // new thread
.doOnTerminate(...) //new thread
.doFinally(...) //new thread
.subscribe(...); // new thread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment