Angular 6 Changes - New Updates to RxJS

August 23, 2018

Guaranteed Wins

Angular 6 brings with it some changes to Observables and Operators in RxJS(The Reactive Extensions library).

The version of RxJS required by Angular 6 is RxJS6; this version has some significant, potentially breaking changes from RxJS 5.

But wait - before you get too stressed out, you should know up front that there is a simple way to ensure backward-compatibility. All you need to do is run the following line in terminal from your project directory:

npm install --save rxjs-compat

This installs the rxjs-compat package, which will make your code automatically compatible with RxJS6. No other changes required!

What’s Different

Now that the issue of backward compatibility is settled, let’s move on to a look at what we need to start doing differently in Angular 6 when working with observables:

File Structure

The first thing that should be mentioned about the update to RxJS6 is that the RxJS library has made a big change in file structure that will affect our import statements. Instead of importing Observable and Subject from subfolders within RxJS, we now import them directly:

import { Observable } from 'rxjs/Observable';
becomes
import { Observable } from 'rxjs';

The import path for operators has also changed. Operators are now stored in a common subfolder: the new import statements look like this:

import { map } from 'rxjs/operators';

These file changes let us import smaller code segments, leading to reduced bundle sizes.

Operator Name Changes

Another significant change in RxJS6 involves renaming a number of operators and observable creation methods. Because these are getting called differently, names that conflicted with reserved JS words had to be changed. So do() is now tap(), and finally() is now finalize().

Here is the complete list of name changes:

// old name
throw()
// new name
throwError()

// old name
fromPromise()
// new name
from()

// old name
catch()
// new name
catchError()

// old name
do()
// new name
tap()

// old name
finally()
// new name
finalize()

// old name
switch()
// new name
switchAll()

Using Operators

The name changes were a result of a change in the way operators are used in RxJS. Here’s how operators were used prior to RxJS6:

observable
  .do(logger.log(x))
  .map(x => x - 5 )
  .subscribe(x => {
    doSomething(x);
  });

Instead of being called directly on the observable, the methods are called as arguments inside a .pipe() function. The methods are called in the order they are listed.

observable
  .pipe(
    tap(logger.log(x)),
    map(x => x - 5 )
  )
  .subscribe(x => {
    doSomething(x);
  });

Nothing too complicated to implement - and remember, backward compatibility is a breeze!


John D Potts

John D Potts

Web developer and speaker in Charlotte, NC.