问题
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 operatorsubscribeOn
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 useobserveOn()
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