An observable and the operators you use on it will execute and notify observers on the same thread on which the subscribe operator is being used.
Schedulers are an abstraction that let you specify distinct queues on which to perform work. It is always a good idea to move all the intensive work off the main thread to keep it as responsive as possible for users, and schedulers make it easy to do this. They can be Serial or Concurrent.
You will use a serial scheduler if you want to ensure that work is carried out on that queue in the order it was added to the queue, otherwise you will typically just use a concurrent queue.
There are built-in scheduler types that work with Grand Central Dispatch (GCD) queues and NSOperationQueues. These are as listed:
- SerialDispatchQueueScheduler, which will dispatch work on a specified serial dispatch queue
- ConcurrentDispatchQueueScheduler, which will dispatch work on a concurrent dispatch queue
- OperationQueueScheduler, which will perform the work on a specified NSOperations queue
You can also create your own custom schedulers by conforming to the ImmediateScheduler protocol.
You also have access to a couple of helpful singletons that can be useful for common needs, such as the following:
CurrentThreadScheduler, which represents the current thread and is the default scheduler, and MainScheduler, which represents the main thread typically used for all UI-related work.
To specify a scheduler on which a subscription is created, it's handled or executed and is disposed of using the suscribeOn operator. This operator is not used normally, instead observeOn is used most of the time; it specifies the scheduler about the next, error, and completed events. The important thing to remember is that subscribeOn will direct which subscription is running on which scheduler, whereas observeOn only directs which scheduler to use after or below where observeOn is used in a chain. We will work with more marble diagrams and code blocks to revisit these concepts in the upcoming sections.