混搭 RxJava 订阅线程

Mix and match RxJava subscription threads

是否可以在 RxJava 中混合和匹配调度程序线程。基本上我想在 Android.

上做类似下面的事情
uiObservable
    .switchMap(o -> return anotherUIObservable)
    .subscribeOn(AndroidSchedulers.mainThread())
    .switchMap(o -> return networkObservable)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(result -> doSomething(result))

在同一个订阅中可以吗?

是的,在您完全理解逻辑之后,这是可能的,而且非常容易。但是您可能有点混淆 observeOn() 和 subscribeOn() 运算符:)

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))

也许这就是你想要的:

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))

奖励:我已经写了关于这些运算符的文章 a post,希望对您有所帮助