Understanding Types of the Rx Java Scheduler

Reading Time: 3 minutes

What is Scheduler in Rx Java

Scheduler are one of the main components in RxJava. They are responsible for performing operations of Observable on different threads. They help to offload the time-consuming onto different threads.

How default thread works in Rx Java

Rx is single-threaded by default. It implies that an Observable and the chain of operators that we can apply to it. That will notify its observers on the same thread on which its subscribe() method is called.

The observeOn and subscribeOn methods take as an argument a Scheduler, that, as the name suggests. It is a tool that we can use for scheduling individual actions.

We’ll create our implementation of a Scheduler by using the createWorker method, which returns a Scheduler.Worker. A worker accepts actions and executes them sequentially on a single thread.

Types of Scheduler

  • Schedulers.trampoline()

Schedulers.trampoline() method creates and returns a Scheduler. That queues work on the current thread to be executed after the current work completes. In simpler words this scheduler runs the code on current thread. If you have a code running on the main thread. This will add the code block on the queue of main thread.

  • Schedulers.newThread()

This scheduler simply starts a new thread every time it is requested via subscribeOn() or observeOn().

  • Schedulers.computation()

This is quite similar to IO Schedulers as this is backed by thread pool too. The number of threads that can be used is fixed to the number of cores present in the system. Suppose a mobile with two cores. It will have 2 threads in the pool. If two threads are busy then the process will have to wait for them to be available. This limitation makes it a poor fit of IO related things. It is good for performing small calculations.

  • Schedulers.io()

This is similar to the newThread except for the fact that already started threads are recycled. And can possibly handle future requests. Every time a new worker is requested, a new thread is started or the idle one is reused.


Written by 

Sumit Agarwal is a Software Consultant having more than 1+ years of experience. He is good at problem-solving skills. He likes to watch football and cricket. He has mainly experience in Java and Mysql.