RxJS Schedulers

Gili Yaniv
2 min readNov 25, 2021

--

We all know and love RxJS. For those who are less familiar with it, It is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.
There are many blog posts and well-written documentation about this library and its abilities but I felt that there's some kind of a gray area around what are RxJS Schedulers.

In the following article, I’ll explain what is a Scheduler and the difference between the different Schedulers that RxJS gives us.

A Scheduler lets you define in what execution context will an Observable deliver notifications to its Observer.

RxJS official docs give us some blurry explanations about Schedulers.
Let's try to understand it by examing the following code

The order in which the logs are printed is different from the order in our code. How come the observer emits first?

Why is that?

For async operations javascript has 2 queues:

Microtasks
In this queue, you will find async operations such as MutationObserver and Promises. You can think of this queue as “Please do this task ASAP”.

Macrotasks
In this queue, you will find async operations such as setTimeout and setInterval. You can think of this queue as “Please do it later”.

JS call stack fetches asynchronous tasks from these two queues and gives priority to tasks that come from the Microtasks queue. That is why the observable emits first even tough it is defined last.

Now we can understand the order of the printed logs. First the observable is resolved from the Microtask queue and then the animationFrame and setTimeout from the Macrotasks queue.

That's all very nice, But what are RxJS Schedulers?
By setting a Scheduler on an RxJS operation we can define in what queue we would like to run this operation. We can choose a scheduler out of the following options:

  • queueScheduler: Schedules on a queue in the current event frame (trampoline scheduler). Use this for iteration operations.
  • asapScheduler: Schedules on the micro task queue, which is the same queue used for promises. Basically after the current job, but before the next job. Use this for asynchronous conversions.
  • asyncScheduler: Schedules work with setInterval. Use this for time-based operations.
  • animationFrameScheduler: Schedules task that will happen just before next browser content repaint. Can be used to create smooth browser animations.
  • null: By not passing any scheduler, notifications are delivered synchronously and recursively. Use this for constant-time operations or tail-recursive operations.

So now we can use what we've learned and set a different scheduler for our example.

We set an asyncScheduler to our observable, thus it emits last.

You can read more about RxJS Scheduler in the official docs.
I hope you found this article useful, Thanks for reading.

--

--

Responses (1)