doOnSubscribe gets called on main thread
Asked Answered
S

2

16

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?

Swashbuckler answered 28/4, 2018 at 10:37 Comment(0)
D
20

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()
Dunstable answered 28/4, 2018 at 11:4 Comment(1)
hi @akarnokd. I'm still a bit confused with doOnSubscribe, could you please see my question here: #57818545Lornalorne
F
5

By default doOnSubscribe executes on the current thread. To change the thread in which doOnSubscribe is executed put subscribeOn below it.

 Observable.just(1)
            .doOnSubscribe(s -> System.out.println("doOnSubscribe thread " + Thread.currentThread().getName())) //IO thread
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.computation())
            .subscribe(s -> {
                System.out.println("subscribing thread " + Thread.currentThread().getName());//Computation thread
            });
Thread.sleep(100);
Fascist answered 21/2, 2020 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.