Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava onCompleted and onTerminate on main thread

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?

like image 266
kos Avatar asked Nov 02 '15 01:11

kos


1 Answers

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();
like image 169
akarnokd Avatar answered Nov 10 '22 20:11

akarnokd