混合和匹配RxJava订阅线程



是否可以在RxJava中混合和匹配调度程序线程?基本上,我想在Android上做如下的事情:

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

是的,在你完全理解了逻辑之后,这是可能的,而且非常容易。但是你可能会混淆一些操作符:

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

附注:我已经写了一篇关于这些运算符的文章,希望能有所帮助

相关内容

  • 没有找到相关文章

最新更新