2

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?

0xAliHn
  • 18,390
  • 23
  • 91
  • 111
  • anything below onbserveon switches to android main thread – Raghunandan Dec 31 '18 at 05:19
  • Then why state.setValue("") not working? – 0xAliHn Dec 31 '18 at 05:20
  • what is state. also you can log to see on which thread you are on with Thread.currentThread().getName() – Raghunandan Dec 31 '18 at 05:25
  • Each operator's documentation specifies which scheduler it works on. For example, that [delay](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html#delay-long-java.util.concurrent.TimeUnit-) runs on the computation scheduler. – akarnokd Dec 31 '18 at 15:26

1 Answers1

3

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:

enter image description here

0xAliHn
  • 18,390
  • 23
  • 91
  • 111