0

Is it possible to mix and match scheduler threads in RxJava. Basically I want to do something like the following on Android.

uiObservable
    .switchMap(o -> return anotherUIObservable)
    .subscribeOn(AndroidSchedulers.mainThread())
    .switchMap(o -> return networkObservable)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(result -> doSomething(result))

Is that possible within the same subscription ?

Saad Farooq
  • 13,172
  • 10
  • 68
  • 94

1 Answers1

3

Yes it's possible and really easy after you have fully understand the logic. But you probably confuse a bit observeOn() and subscribeOn() operators :)

uiObservable
    .switchMap(o -> return anotherUIObservable)
    .subscribeOn(AndroidSchedulers.mainThread())  // means that the uiObservable and the switchMap above will run on the mainThread.

    .switchMap(o -> return networkObservable) //this will also run on the main thread

    .subscribeOn(Schedulers.newThread()) // this does nothing as the above subscribeOn will overwrite this

    .observeOn(AndroidSchedulers.mainThread()) // this means that the next operators (here only the subscribe will run on the mainThread
    .subscribe(result -> doSomething(result))

Maybe this is what you want:

uiObservable
    .switchMap(o -> return anotherUIObservable)
    .subscribeOn(AndroidSchedulers.mainThread()) // run the above on the main thread

    .observeOn(Schedulers.newThread())
    .switchMap(o -> return networkObservable) // run this on a new thread

    .observeOn(AndroidSchedulers.mainThread()) // run the subscribe on the mainThread
    .subscribe(result -> doSomething(result))

Bonus: I have written a post about these operators, hope it helps

Diolor
  • 13,181
  • 30
  • 111
  • 179