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)
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.
Most helpful comment
delayusesSchedulers.computation()if you don't provide aScheduler. In your first case, you should use.delay(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())if you want to observeonNextin the main thread.