RxJava onCompleted and onTerminate in the main topic

I am using RxJava with Retrofit 2.0 on Android for network requests.

When I create an observable, I add the following to it:

observable = observable .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) 

Then if I add:

 observable = observable.doOnTerminate(new Action0() { @Override public void call() { Log.d("OBS", "[" + Thread.currentThread().getName() + "] onTerminate"); } }); 

Or similar doOnError and doOnCompleted callbacks are executed in the I / O thread, and doOnNext is executed in the main thread.

However, I really want all callbacks to go to the main thread, but execution should remain in the I / O thread.

Is there an elegant solution for this without having to manually transfer my implementations in block to send something to the main thread?

+6
source share
1 answer

You must put your callbacks before any observeOn so that they remain in your previous thread:

 Observable.range(1, 10) .subscribeOn(Schedulers.io()) .doOnTerminate(() -> System.out.println(Thread.currentThread())) .map(v -> v + 1) .observeOn(AndroidSchedulers.mainThread()) .map(v -> Thread.currentThread() + " / " + v) .doOnNext(v -> Log.d("OBS", v)) .subscribe(); 
+8
source

All Articles