doOnSubscribe gets called on main thread

做~自己de王妃 提交于 2019-12-23 09:29:54

问题


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

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.

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


回答1:


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

or

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


来源:https://stackoverflow.com/questions/50075574/doonsubscribe-gets-called-on-main-thread

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