what is a `Scheduler` in RxJS
Solution 1:
Rx schedulers provide an abstraction that allows work to be scheduled to run, possibly in the future, without the calling code needing to be aware of the mechanism used to schedule the work.
Whenever an Rx method needs to generate a notification, it schedules the work on a scheduler. By supplying a scheduler to the Rx method instead of using the default, you can subtly control how those notifications are sent out.
In server-side implementations of Rx (such as Rx.NET), schedulers play an important role. They allow you to schedule heavy duty work on the thread pool or dedicated threads, and run the final subscription on the UI thread so you can update your UI.
When using RxJs, it is actually pretty rare that you need to worry about the scheduler argument to most methods. Since JavaScript is essentially single-threaded, there are not a lot of options for scheduling and the default schedulers are usually the right choice.
The only real choices are:
-
immediateScheduler
- Runs the work synchronously and immediately. Sort of like not using a scheduler at all. Work scheduled thus is guaranteed to run synchronously. -
currentThreadScheduler
- Similar toimmediateScheduler
in that the work is run immediately. However, it does not run work recursively. So, if the work is running and schedules more work, then that additional work is put into queue to be run after the current work finishes. Thus work sometimes runs synchronously and sometimes asynchronously. This scheduler is useful to avoid stack overflows or infinite recursion. For exampleRx.Observable.of(42).repeat().subscribe()
would cause infinite recursion if it ran on theimmediate
scheduler, but sincereturn
runs on thecurrentThread
scheduler by default, infinite recursion is avoided. -
timeoutScheduler
- The only scheduler that supports work scheduled to be run in the future. Essentially usessetTimeout
to schedule all work (though if you schedule the work to be run "now", then it uses other faster asynchronous methods to schedule the work). Any work scheduled on this scheduler is guaranteed to be run asynchronously.
There may be some more now, such as a scheduler that schedules work on the browser animation frames, etc.
If you are trying to write testable code, then you almost always want to supply the scheduler argument. This is because in your unit tests, you will be creating testScheduler
instances, which will let your unit test control the clock used by your Rx code (and thus control the exact timing of the operations).