Does the order of subscribeOn and observeOn matter?

无人久伴 提交于 2019-12-02 17:33:47
Jahnold

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!