24 Jul 2024
2 min

Operators – RxJS Reference

Operators

RxJS library implements the Observable primitive and adds operators to enable more efficient workflows when dealing with streams of asynchronous events. While Observable is the foundation, operators allow composing and transforming streams of data in a declarative manner.

Operators are chained together using pipe method that is available on Observable. Here’s a basic example that transforms and filters a stream of mouse clicks to only notify a subscriber if the click happens inside an element:

const rect = document.querySelector('.rect').getClientRects();

function isEventInElement(rect, clientX, clientY) {
   if (clientX < rect.left || clientX >= rect.right) return false;
   if (clientY < rect.top || clientY >= rect.bottom) return false;
   return true;
}

fromEvent(document, 'click').pipe(
   map((event: MouseEvent) => {
       return {x: event.clientX, y: event.clientY};
   }),
   filter(({x, y}) => {
       return isEventInElement(rect[0], x, y);
   })
).subscribe(() => console.log('inside'));

There are many different categories of operators. Here are some of the most common operators placed under their respective categories:

An operator is a function that takes a source observable, creates a new observable inside and connects both observables through a subscription. This new observable is returned from the operator function and passed down an operators chain. The signature for an operator function looks like this:

(source: Observable<T>) => Observable<R>

Here’s a super simple operator that simply connects a source observable with a observer (subscriber) and passes the value along the chain:

function operator(source) {
   return new Observable(observer => {
       source.subscribe((value) => {
           observer.next(value);
       });
   });
}

This operator would be used like this:

fromEvent(document, 'click').pipe(
   operator
).subscribe((value: MouseEvent) => console.log(value.clientX));

It’s not a complete implementation since we don’t handle complete and error events. Nevertheless, this implementation clearly demonstrates the essence of operators. We have a new Observable created and returned and the subscription to the source is established.

In RxJS library all operators are implemented as higher-order functions that can take parameters and return an operator function. For example, the map operator takes a function this transforms a value that goes through the operator.

We can easily turn our custom operator from above into a higher-order function take takes a transformation function similar to the map operator:

function customOperator(transform) {
   return (source) => {
       return new Observable(observer => {
           source.subscribe((value) => {
               const transformed = transform(value);
               observer.next(transformed);
           });
       });
   };
}

That will be used like this:

fromEvent(document, 'click').pipe(
   customOperator((event) => event.clientX)
).subscribe((value: MouseEvent) => console.log(value));

To learn more about building your own operators check out this article.

Frequently asked questions

How do I chain RxJS operators on an Observable?

Chain RxJS operators by passing them as arguments to the pipe() method available on an Observable. Each operator receives the source stream and returns a new Observable, so fromEvent(document, 'click').pipe(map(...), filter(...)) applies map first and then filter. The chained result is what you subscribe to, and the source Observable itself stays unchanged.

What is an RxJS operator function and what is its signature?

An RxJS operator is a function with the signature (source: Observable<T>) => Observable<R>, which takes a source Observable and returns a new Observable. Inside, it creates a new Observable and subscribes to the source, forwarding values with observer.next(). Operators are passed to pipe(), and the returned Observable is then passed down the operator chain.

How do I create a custom RxJS operator that accepts parameters?

Create a custom operator as a higher-order function that accepts parameters and returns an operator function taking a source Observable. Inside, return new Observable(observer => ...) and subscribe to the source, transforming each value before calling observer.next(). This mirrors how built-in operators like map work, and you use it inside pipe() like any other operator.

Why is my custom RxJS operator missing complete and error handling?

A minimal custom operator that only calls observer.next() does not forward complete or error notifications from the source, so the subscriber never learns that the stream ended or failed. The article presents this version as a simplified demonstration of the core idea. A production operator should also forward observer.complete() and observer.error() from the source subscription.

Which RxJS operators belong to the filtering, transformation, and combination categories?

RxJS groups operators by purpose: filtering includes filter, take, and debounceTime; transformation includes map, switchMap, and scan; and combination includes concatAll, withLatestFrom, and zip. Creation operators such as of, from, and fromEvent produce Observables, while catchError, retry, and retryWhen handle errors.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.