RxJS Mastery – #67 subscribeOn

The RxJS subscribeOn operator returns the source Observable in a modified state such that the subscription happens with a specified scheduler.

RxJS subscribeOn to customize the emission of values

As schedulers control the speed and order of emissions, this can help to customize an existing Observable to one’s needs. Let us see that in action. The of operator synchronously emits values. We can change that by specifying the asyncScheduler with the help of subscribeOn.

const a$ = of(1, 2, 3).pipe(subscribeOn(asyncScheduler));
const b$ = of(4, 5, 6);

merge(a$, b$).subscribe(console.log);

The output of the above code does not start with 1, 2, 3. But it looks like the following:

4
5
6
1
2
3

Because the values of b$ are emitted synchronously they come first. On the other hand, the values of a$ are put onto the event loop of JavaScript and therefore appear asynchronously.

This post is part of the RxJS mastery series. As always the code examples can be found on GitHub.