Does the order of subscribeOn and observeOn matter? Does the order of subscribeOn and observeOn matter? multithreading multithreading

Does the order of subscribeOn and observeOn matter?


Where you call subscribeOn() in a chain doesn't really matter. Where you call observeOn() does matter.

subscribeOn() tells the whole chain which thread to start processing on. You should only call it once per chain. If you call it again lower down the stream it will have no effect.

observeOn() causes all operations which happen below it to be executed on the specified scheduler. You can call it multiple times per stream to move between different threads.

Take the following example:

doSomethingRx()    .subscribeOn(BackgroundScheduler)    .doAnotherThing()    .observeOn(ComputationScheduler)    .doSomethingElse()    .observeOn(MainScheduler)    .subscribe(//...)
  • The subscribeOn causes doSomethingRx to be called on the BackgroundScheduler.
  • doAnotherThing will continue on BackgroundScheduler
  • then observeOn switches the stream to the ComputationScheduler
  • doSomethingElse will happen on the ComputationScheduler
  • another observeOn switches the stream to the MainScheduler
  • subscribe happens on the MainScheduler


Yea you're correct. observeOn will only receive the events on the thread you've specified, whereas subscribeOn will actually execute the work within the specified thread.


.subscribeOn() operator affect on which sheduler chain will be created (to the left of it) and it work once. .observeOn() influence operator to the right of it - on which schedulers data will be processed after operator.