RxJS Pipeable Operators

sachila ranawaka
2 min readJun 19, 2018

--

When we use Observable in our application sometimes operators like map, filter, catch, etc.. has been used along with it. We called these operators Lettable operators. These operators allow composing observable chain to manipulate data or handle events. If we want use observables and operators we need to use the RXJS library. The RxJS library is large. Size matters when building a production application and deploying it. Especially if we are deploying it to the mobile devices. It’s necessary to only add the operators we use.

In the earlier versions when RxJS bundle is imported, all operators will have been added to Observable.prototype.

import * as Rx from “rxjs”;this.http.get(‘path’)
.map(p => p.json())
.catch(error => Rx.Observable.of(null));
.subscribe(data => console.log(data))

The problem with this approach is that the applications will contain everything that’s in RxJS, even if it’s not required. All the operators (map, filter, etc..) are a patch to the observable.prototype. But If we segregate this bundle into individual operators and import them separately we can prevent the additional overhead. Also, we can detect the unused imports more reliably and we can even add lint rule to validate the unused imports. Because of that angular team segregate this bundle from version 5.5 and they rename this to Pipeable operators.

Pipeable functions are pure functions. They do not patch the observable. It uses ES6 import standard to import the operators. When we use pipeable operators we have to use pipe() function. Because once we import the operators they wrap into pipe function. Pipe operator is simply a function that returns a function with a signature. Pipe function is already built into Observable so we don’t need to import it separately. Pipe function can take a number of parameters in chainable sequence.

import {  map, catchError } from 'rxjs/operators'; this.http.get(‘path’)
.pipe(
catchError(error => this.handleError(error)),
map(item => $ { item.name }: $$ { item.price })
).subscribe(
item => console.log(item)
)

Now in case if you remove the map operator from the code and not from the import, it will do us no harm. Because now the tree shaking module can identify that the imported operator is not used in our code. So the map operator will not include into the bundles. Now, the code is much more cleaner.

--

--