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.
<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.
fromEvent
: the Observable in the demo will listen on thekeyup
event.map
: we only care about the value we input, so we usemap
to get the value from the object.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.distinctUntilChanged
: we only care about when the value changes.
Try yourself
You can follow the steps below to test it:
Input
1
, the console will show1
.Type
2
,3
,4
quickly, the console will only show1234
because ofdebounceTime(500)
.Type
5
, and delete5
quicly, the console will not show anything which is because ofdistinctUntilChanged()
.
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
To have an interactive learning experience for RxJS operators, you can use