doOnSubscribe 在主线程上被调用 [英] doOnSubscribe gets called on main thread

查看:35
本文介绍了doOnSubscribe 在主线程上被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了多篇博文和文档后,我得出的结论是以下 doOnSubscribe 将在工作线程上执行:

After reading multiple blog posts and documentation, I came to the conclusion that following doOnSubscribe will be executed on a worker thread:

Observable.just(1)
            .observeOn(Schedulers.io())
            .doOnSubscribe(__ -> Log.d("Testing", "Testing")) // Shouldn't this be on worker thread?
            .subscribe();

但是在调试之后,我看到 doOnSubscribe 是在主线程上执行的.我认为 doOnSubscribe 与其他运算符类似,因此与 subscribeOnobserveOn 结合使用时具有类似的线程行为.

But after debugging, I see doOnSubscribe is executed on main thread. I thought doOnSubscribe is similar to other operators and hence has similar threading behavior when coupled with subscribeOn and observeOn.

我错过了什么?如何将 doOnSubscribe 执行移动到后台线程?

What am I missing? How can I move doOnSubscribe execution to background thread?

推荐答案

subscribeOnobserveOndoOnSubscribe 没有影响,因为它们之间的连接在调用者线程上建立操作符以支持立即取消.您必须以某种方式将订阅推迟到 doOnSubscribe,例如:

subscribeOn and observeOn have no effect on doOnSubscribe because the connection between operators are established on the caller thread in order to support immediate cancellation. You have to defer the subscription to a doOnSubscribe in some way, e.g.:

Observable.defer(() ->
    Observable.just(1)
    .doOnSubscribe(s -> Log.d("Testing", "Testing"))
)
.subscribeOn(Schedulers.io())
.subscribe();

Observable.just(1)
.subscribeOn(Schedulers.io())
.flatMap(v ->
    Observable.just(1)
    .doOnSubscribe(s -> Log.d("Testing", "Testing"))
)
.subscribe()

这篇关于doOnSubscribe 在主线程上被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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