Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doOnSubscribe gets called on main thread

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?

like image 211
Dhruv Jagetiya Avatar asked Apr 28 '18 10:04

Dhruv Jagetiya


1 Answers

By default doOnSubscribe executes on the current thread. To change the thread in which doOnSubscribe is executed put subscribeOn below it. Tested with rxjava2 version 2.2.14

 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);
like image 171
Bek Avatar answered Oct 24 '22 20:10

Bek