RxJS 5

Angular 2 is RxJS 5 powered. And ngrx we will add in next part is also RxJS powered. So before going to next chapter, let's introduce RxJS first.

RxJS is a reactive programming library for JavaScript.

Reactive programming is programming with asynchronous data streams. And A stream is simply a collection that arrives over time.

A simple demo

We will use this demo to explain RxJS 5.

This demo is a pure RxJS 5 app without Angular 2.

Live demo

<input type="text" id="myInput" />
const input = document.getElementById('myInput');

const stream$ = Rx.Observable
  .fromEvent(input, 'keyup')
  .map(i => i.currentTarget.value)
  .debounceTime(500)
  .distinctUntilChanged();

const subscribe = stream$.subscribe(val => {
  console.log(val);
});

Observalbe is a representation of any set of values over any amount of time. It is the most basic building block of RxJS.

The dollar sign $ suffixed to a name is a soft convention to indicate that the variable is a Observalbe. In this demo, it is stream$.

fromEvent, map, debounceTime, and distinctUntilChanged are operators. They are used in a chain which likes a data stream.

  1. fromEvent: the Observable in the demo will listen on the keyup event.
  2. map: we only care about the value we input, so we use map to get the value from the object.
  3. debounceTime: the debounceTime operator will emit the last value received only after a 500ms has passed. The timer will reset each time a value is received from the source.
  4. distinctUntilChanged: we only care about when the value changes.

Try yourself

You can follow the steps below to test it:

  1. Input 1, the console will show 1.

  2. Type 2, 3, 4 quickly, the console will only show 1234 because of debounceTime(500).

  3. Type 5, and delete 5 quicly, the console will not show anything which is because of distinctUntilChanged().

Learn more

To have a general understanding of RxJS, you can read

The introduction to Reactive Programming you've been missing

If you meet any RxJS operator you don't understand or want to learn operators, we highly recommend you read

Learn RxJS

To have an interactive learning experience for RxJS operators, you can use

RxMarbles - Interactive diagrams of Rx Observables

results matching ""

    No results matching ""