Rxjava: Why does delay operator not use specified scheduler?

Created on 28 Sep 2014  Â·  3Comments  Â·  Source: ReactiveX/RxJava

The following behavior surprised me. Why is this the case?

Observable.just("test")
        .observeOn(AndroidSchedulers.mainThread())
        .delay(1, TimeUnit.SECONDS)
        .doOnNext(new Action1<String>() { @Override 
            public void call(String s) {
                Log.e("doOnNext", Thread.currentThread().getName());
            }
        })
        .subscribe();

results in:
E/doOnNext﹕ RxComputationThreadPool-1
(unexpected behavior)

Swapping delay and observeOn:

Observable.just("test")
        .delay(1, TimeUnit.SECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Action1<String>() { @Override 
            public void call(String s) {
                Log.e("doOnNext", Thread.currentThread().getName());
            }
        })
        .subscribe();

results in:
E/doOnNext﹕ main
(expected behavior)

Most helpful comment

delay uses Schedulers.computation() if you don't provide a Scheduler. In your first case, you should use .delay(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) if you want to observe onNext in the main thread.

All 3 comments

Why does it surprise you? When you do observeOn you ask to be moved to a different thread, which is exactly what happens. In general xs.observeOn(s).ys will run ys on the scheduler s.

delay uses Schedulers.computation() if you don't provide a Scheduler. In your first case, you should use .delay(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) if you want to observe onNext in the main thread.

@zsxwing Thanks, I didn't notice that the delay operator needs a scheduler to operate on, I kind of naively assumed that a delay operation wouldn't need a particular scheduler. The JavaDoc documentation is a bit clearer on that than the Wiki documentation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ZakTaccardi picture ZakTaccardi  Â·  3Comments

nltran picture nltran  Â·  4Comments

dimsuz picture dimsuz  Â·  4Comments

philleonard picture philleonard  Â·  3Comments

hoc081098 picture hoc081098  Â·  3Comments