interval() operator

In JavaScript, there is a setInterval() function that enables you to execute code at regular intervals, up until the point that you choose to stop it. RxJS has an operator that behaves just like that, the interval() operator. It takes one parameter: normally, the number of milliseconds between emitted values. You use it in the following way:

// time/interval.js

let stream$ = Rx.Observable.interval(1000);

// emits 0, 1, 2, 3 ... n with 1 second in between emits, till the end of time
stream$.subscribe(data => console.log(data));

A word of caution is that this operator will continue emitting until you stop it. The best way to stop it is to combine it with a take() operator. A take() operator takes a parameter that specifies how many emitted values it wants before stopping. The updated code looks like this:

// time/interval-take.js

let stream$ = Rx.Observable.interval(1000)
.take(2);

// emits 0, 1, stops emitting thanks to take() operator
stream$.subscribe(data => console.log(data));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.219