How RXJava Scheduler/Threading works for different operator?

爷,独闯天下 提交于 2019-12-24 11:57:25

问题


Can anyone please help me to explain which scheduler are running below code?

Completable.complete()                 
.subscribeOn(http://Schedulers.io  ())                 
.observeOn(AndroidSchedulers.mainThread())                 
.delay(5000, TimeUnit.MILLISECONDS)                 
.doOnComplete(() -> liveDataState.postValue(""))                 
.subscribe()

My question is which schedulers are delay(), doOnComplete() and subscribe() are using io or mainThread?


回答1:


After digging into RxJava threading last two days found the rule of thumbs for handling RxJava Threading/Scheduling:

  • observeOn works only downstream operator
  • subscribeOn works for both downstream and upstream operator
  • Consecutive/Multiple subscribeOn do not change the thread
  • Consequent observeOn do change the thread for downstream oerator
  • Unlike with subscribeOn(), we can use observeOn() multiple times for seamless thread switching
  • Operator like delay(), interval() have default scheduler and can change the downstream scheduler as well

So, for my case:

Completable.complete()   // IO scheduler based on subscribeOn scheduler           
.subscribeOn(http://Schedulers.io  ())                 
.observeOn(AndroidSchedulers.mainThread())                 
.delay(5000, TimeUnit.MILLISECONDS)   // Default Computation scheduler              
.doOnComplete(() -> liveDataState.postValue(""))  // Computation scheduler by delay scheduler             
.subscribe()  // Computation scheduler by delay as well

Also, you can look into the marble diagram for more understanding:



来源:https://stackoverflow.com/questions/53983854/how-rxjava-scheduler-threading-works-for-different-operator

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