Search code examples
rxjsrxjs-lettable-operators

Centrally importing rxjs lettable operators


Im used to using the old rxjs syntax where all method calls are chained, and where i can centrally import all operators.

In a new application, i now started using the "lettable operators" using the pipe method on the Obsrvable, but i dont succeed in importing those operators centrally.

So, in a certain component i am using map and mergeMap, and import them like this:

import { map } from 'rxjs/operators/map';
import { mergeMap } from 'rxjs/operators/mergeMap';

If i remove these imports from my component file and put them in my main.ts for example, compilation fails because those methods are not found ... This used to be simple before the lettable operators. What am i missing?


Solution

  • With the old operators, importing them consisted in monkey-patching the Observable class with a new method. You relied on the bad practice of importing them in one file, and using them in a separate one. This was a bad practice because if, let's say, the distinctUntilChanged operator was only used in one file, and you decided not to use it anymore, or simply deleting the file, the central place still imported it, for nothing, making your bundle larger than necessary.

    Now the operators are standalone top-level functions. You simply need (as you should have done with the old ones) to import them where you use them. This is needed by TypeScript so that it knows which function you're using (several top-level functions of several libraries could be named map() or of() or filter()), and it's also required for the bundler to know what to include in the bundle.

    See https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#why for a longer explanation.

    In short, just get used to it: classes, functions, variables and constants you use in one module (i.e. file) must be imported by that module.

    Decent IDEs add the necessary imports automatically. If you're typing your imports by hand, then you need to use better tools.