RxJS Mastery – #66 observeOn

The RxJS observeOn operator remits all notifications from the source using a specified scheduler.

RxJS observeOn with animationScheduler for smooth animations

If the scheduler of the source Observable cannot be adapted, the observeOn operator comes into play. The primary use case for the RxJS observeOn operator is the specification of the animationScheduler for certain Observables.

const progressBarDiv = new HTMLDivElement();

interval(10)
    .pipe(observeOn(animationFrameScheduler))
    .subscribe(newHeight => {
        progressBarDiv.style.height = newHeight + 'px';
    });

This helps to get rid of choppy animations because the value emission is better synchronized with the rendering behavior of the browser:

Prefer the delay operator over the delay parameter of observeOn

In addition to the scheduler parameter, observeOn would also support a delay. This delay is applied to every source notification, including errors.

observeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T>

This is the main reason why the delay operator is recommended over the delay parameter of observeOn. Usually, you do not want to delay errors. Besides the delay operator is also better understood.

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