RxJS Mastery – #46 ignoreElements

RxJS Mastery lesson title ignoreElements operator

The RxJS ignoreElements operator is another filter operator. If you are not interested in any values this operator can be used. It filters out everything but error and complete notifications.

RxJS ignoreElements never calls the observer’s next

Because the ignoreElements operator suppresses all values it is never invoking the observer’s next handler. Hence the Observable below just completes after 4 time frames, but doesn’t emit any value:

const result$ = interval(1).pipe(
    take(4),
    ignoreElements(),
);

expectObservable(result$).toBe('----|'); 

RxJS ignoreElements only cares about complete and error

No value is going beyond the ignoreElements operator, but errors are reaching that point:

const result$ = of(1, 'hello', true, 2, false).pipe(
    concatMap(value => {
        if (value === 2) {
            throw Error('error from the source!');
        }
        return of(value);
    }),
    ignoreElements(),
);

expectObservable(result$).toBe('#', null, new Error('error from the source!'));

In the example above the source Observable is emitting various values. If the value ‘2’ is emitted an error is thrown. This is the only notification that is considered in the result$ Observable. As you can see in the assertion the second parameter is null and indicates that no value was emitted. The error thrown by the source Observable is visible in the result$ Observables’ output.

Exercise for the RxJS ignoreElements operator 💪

Think about where to use the ignoreElements operator. In which cases do you only want to know about completion and errors, but not about values?

As always the code examples can be found on GitHub.