I'm using RxJava with Retrofit 2.0 on Android for network requests.
When I'm creating the observable, I add the following to it:
observable = observable
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
Then if I add a:
observable = observable.doOnTerminate(new Action0() {
@Override
public void call() {
Log.d("OBS", "[" + Thread.currentThread().getName() + "] onTerminate");
}
});
Or similar for doOnError
and doOnCompleted
the callbacks are executed on the IO thread, while doOnNext
is executed on the main thread.
However, what I really want is for all callbacks to go to the main thread, but the execution should stay on the IO thread.
Is there an elegant solution to this without having to manually wrap my implementations with a block to post something to the main thread?
You should place your callbacks before any observeOn
so they'll stay on its 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With