Use functions for readable RxJs operator chains

When you have complex RxJs operator chains, a good idea is to refactor them into simple functions. This can also favor code reuse for simple scenarios such as the following example.

Say we have a User object with the following shape:

We receive that object through an Observable; all we want from it is the user’s age. Using Rxjs (and date-fns), we could do something like this:

This works, but it’s not instantly apparent that we’re computing the age of the user, and if we need similar code elsewhere, we’d have to copy-paste that line of code, which is terrible.

Instead, we could create a function with an explicit name:

And then use it as our new custom operator function:

We can improve the signature of our function for type safety purposes, too:

You can see that code in action on Stackblitz here.

Obviously, the approach makes even more sense when you have several operators, and you can even combine such operator functions with other operator functions:

Now we have beautiful, maintainable code that can be read without documentation.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.