Let's explore how Schedulers work by checking out a few examples.
Let's run the following code:
Observable.just("First item", "Second item")
.doOnNext(e -> Log.d("APP", "on-next:" +
Thread.currentThread().getName() + ":" + e))
.subscribe(e -> Log.d("APP", "subscribe:" +
Thread.currentThread().getName() + ":" + e));
The output will be as follows:
on-next:main:First item
subscribe:main:First item
on-next:main:Second item
subscribe:main:Second item
Now let's try changing the code as shown:
Observable.just("First item", "Second item")
.subscribeOn(Schedulers.io())
.doOnNext(e -> Log.d("APP", "on-next:" +
Thread.currentThread().getName() + ":" + e))
.subscribe(e -> Log.d("APP", "subscribe:" +
Thread.currentThread().getName() + ":" + e));
Now, the output should look like this:
on-next:RxCachedThreadScheduler-1:First item
subscribe:RxCachedThreadScheduler-1:First item
on-next:RxCachedThreadScheduler-1:Second item
subscribe:RxCachedThreadScheduler-1:Second item
We can see how the code was executed on the main thread in the first case and on a new thread in the next.
Android requires that all UI modifications should be done on the main thread. So, how can we execute a long-running process in the background but process the result on the main thread? That can be done with .observeOn() method:
Observable.just("First item", "Second item")
.subscribeOn(Schedulers.io())
.doOnNext(e -> Log.d("APP", "on-next:" +
Thread.currentThread().getName() + ":" + e))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(e -> Log.d("APP", "subscribe:" +
Thread.currentThread().getName() + ":" + e));
The output will be as illustrated:
on-next:RxCachedThreadScheduler-1:First item
on-next:RxCachedThreadScheduler-1:Second item
subscribe:main:First item
subscribe:main:Second item
You will note that the items in the doOnNext block were executed on the RxThread, and the subscribe block items were executed on the main thread.
We will cover Schedulers more and with examples in the later chapters when we will start working with databases.