Specifying a scheduler

To specify a scheduler on which a subscription is created, handler-executed, and disposed of, we use the subscribeOn operator. This is not normally used; instead, we just use ObserverOn, which specifies the scheduler events: next, error, and completed. The important thing to remember is that subscribeOn will direct which scheduler a subscription operates, whereas ObserveOn will only direct which scheduler to use after or below where ObserveOn is used in a chain. Let's look at this in a marble diagram first and then jump into a code example in the coming section.

We are starting on in the main thread, which is represented by the timeline here:

We will call ObserverOn and specify scheduler1, as shown:

Imagine that we will do some intensive work here, so we are specifying the background queue to receive the events on for a map operation, as follows:


Finally, we will call subscribeOn and specify scheduler2. We specified where we want subscriptions to be created, where the handlers are executed, and where they will be disposed of. This is not normally necessary; we are just demonstrating how it works:

Using the subscribeOn operator here will direct subscriptions for the entire chain. That means we will no longer be on the main thread initially:

It will be on the queue, as shown in the preceding diagram by scheduler2. We are still observing on scheduler1; nothing has changed there, and finally we will use ObserveOn again to receive the transformed elements from the map operation back on the main thread, as illustrated:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset