Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make countdown timer with RxJS Observables?

Tags:

I'm struggling to create a countdown timer using Observables, the examples at http://reactivex.io/documentation/operators/timer.html do not seem to work. In this specific example the error related to timerInterval not being a function of the Observable returned from timer.

I have also been experimenting with other approaches and the best I've come up with is:

Observable.interval(1000).take(10).subscribe(x => console.log(x)); 

The problem here is it counts up from 0 to 10 and I want a countdown timer e.g. 10,9,8...0.

I've also tried this but the timer does not exist for type Observable

Observable.range(10, 0).timer(1000).subscribe(x => console.log(x)); 

As well as, which produces no output at all.

Observable.range(10, 0).debounceTime(1000).subscribe(x => console.log(x)); 

To clarify I need help with ReactiveX's RxJS implementation, not the MircoSoft version.

like image 522
Jon Miles Avatar asked Jan 21 '16 10:01

Jon Miles


People also ask

How do I stop Observable timer?

There're are basically two ways: call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.

What is of () RxJS?

RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.


2 Answers

You were on the right track - your problem was that timer does not exist on the prototype (and thereby on Observable.range())but on Observable (see the RxJS docs). I.e. jsbin

const start = 10; Rx.Observable   .timer(100, 100) // timer(firstValueDelay, intervalBetweenValues)   .map(i => start - i)   .take(start + 1)   .subscribe(i => console.log(i));  // or Rx.Observable   .range(0, start + 1)   .map(i => start - i)   .subscribe(i => console.log(i)); 
like image 105
Niklas Fasching Avatar answered Sep 25 '22 18:09

Niklas Fasching


Using timer, scan and takeWhile if you don't want to depend on a variable for your starting time, the 3rd argument in scan is the starting number

timer$ = timer(0, 1000).pipe(   scan(acc => --acc, 120),   takeWhile(x => x >= 0) ); 

Check it out on Stackblitz

like image 35
Matt Bogenhagen Avatar answered Sep 22 '22 18:09

Matt Bogenhagen