混合搭配 RxJava 订阅线程 [英] Mix and match RxJava subscription threads

查看:43
本文介绍了混合搭配 RxJava 订阅线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 RxJava 中混合和匹配调度程序线程.基本上我想在 Android 上做类似下面的事情.

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 ?

推荐答案

是的,在您完全理解逻辑之后,这是可能的,而且非常简单.但是您可能会混淆observeOn() 和subscribeOn() 运算符:)

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

也许这就是你想要的:

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

这篇关于混合搭配 RxJava 订阅线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆