Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing RxJS using named imports or 'add' string

Whats the difference between importing RxJS functions and methods using only a string and importing using a named import. For example:

Using the 'add' string:

import 'rxjs/add/operator/map'

Using a named import

import { merge } from 'rxjs/observable/merge'

An individual method only works one way but I can't work out how to tell which way a particular method needs to be imported. Is there a way to determine which method to use, and what's the difference?

like image 660
Geraint Anderson Avatar asked Apr 07 '18 14:04

Geraint Anderson


1 Answers

The first import will patch the Observable prototype with the map method so it will be available on all instances of this type.

The second one is importing just a function that can be called with some arguments and will return an Observable.

Patching the prototype does not work well with things like tree shaking so in the latest versions of RxJs the pipe method was added and all the imports are named.

Example from RxJs readme:

import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

range(1, 200)
  .pipe(filter(x => x % 2 === 1), map(x => x + x))
  .subscribe(x => console.log(x));
like image 200
Adrian Fâciu Avatar answered Oct 05 '22 23:10

Adrian Fâciu