Schedulers

Schedulers are the easiest way to bring multi-threading into your apps. They are an important part of RxJava and they play perfectly along with Observables. They provide a handy way to create concurrent routines without having to deal with implementations, synchronizations, threading, platform limitations, and platform changes.

RxJava offers five kinds of Schedulers:

  • .io()
  • .computation()
  • .immediate()
  • .newThread()
  • .trampoline()

Let's take a look at them one by one.

Schedulers.io()

This Scheduler is meant for I/O operations. It's based on a thread pool that adjusts its size when necessary, growing or shrinking. This is the Scheduler we are going to use to fix the StrictMode violation we saw previously. As it's specific for I/O, it's not the default for any RxJava method; it's up to the developer to use it properly.

It's important to note that with the thread pool unbounded, a large amount of scheduled I/O operations will create a large amount of threads and memory usage. As always, we have to look for the effective balance between performance and simplicity.

Schedulers.computation()

This is the default scheduler for every computational work that is not related to I/O. It's the default for a lot of RxJava methods: buffer(), debounce(), delay(), interval(), sample(), and skip().

Schedulers.immediate()

This Scheduler allows you to immediately start the specified work on the current thread. It's the default Scheduler for timeout(), timeInterval(), and timestamp().

Schedulers.newThread()

This Scheduler is what it looks like: it starts a new thread for the specified work.

Schedulers.trampoline()

When we want to execute a task on the current thread, but not immediately, we can queue it with .trampoline(). This Scheduler will process its queue and run every queued task sequentially. It's the default Scheduler for repeat() and retry().

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

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