Mix and match RxJava subscription threads

拥有回忆 提交于 2019-12-13 07:42:12

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/32417958/mix-and-match-rxjava-subscription-threads

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