In RxJava there are 5 different schedulers to choose from:
immediate(): Creates and returns a Scheduler that executes work immediately on the current thread.
trampoline(): Creates and returns a Scheduler that queues work on the current thread to be executed after the current work completes.
newThread(): Creates and returns a Scheduler that creates a new Thread for each unit of work.
computation(): Creates and returns a Scheduler intended for computational work. This can be used for event-loops, processing callbacks and other computational work. Do not perform IO-bound work on this scheduler. Use Schedulers.io() instead.
io(): Creates and returns a Scheduler intended for IO-bound work. The implementation is backed by an Executor thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO. Do not perform computational work on this scheduler. Use Schedulers.computation() instead.
The first 3 schedulers are pretty self explanatory; however, I'm a little confused about computation and io.
java.io
) and files (java.nio.files
)? Is it used for database queries? Is it used for downloading files or accessing REST APIs?Great questions, I think the documentation could do with some more detail.
io()
is backed by an unbounded thread-pool and is the sort of thing you'd use for non-computationally intensive tasks, that is stuff that doesn't put much load on the CPU. So yep interaction with the file system, interaction with databases or services on a different host are good examples. computation()
is backed by a bounded thread-pool with size equal to the number of available processors. If you tried to schedule CPU intensive work in parallel across more than the available processors (say using newThread()
) then you are up for thread creation overhead and context switching overhead as threads vie for a processor and it's potentially a big performance hit.computation()
for CPU intensive work only otherwise you won't get good CPU utilization.io()
for computational work for the reason discussed in 2. io()
is unbounded and if you schedule a thousand computational tasks on io()
in parallel then each of those thousand tasks will each have their own thread and be competing for CPU incurring context switching costs.