Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop an Observable interval manually?

Tags:

angular

I am currently trying to make a 20 second timer like this:

this.timer = Observable.interval(1000).take(20).map((tick) => tick+1).subscribe((tick) => {
    this.reverseTimer = 20-tick;
})

This is fine if I let the Observable reach 20 every time, but sometimes, I want to end the timer early. Right now, I can't stop the timer until it stops itself after 20 seconds.

Right now, I am hiding the timer in the display when I want it to stop, but I need it to be able to restart. If I try to restart the timer before 20 seconds, reverseTimer flickers between the new timer and old timer values because I haven't stopped the old timer.

I have tried this.timer.unsubscribe() but I get the error that unsubscribe does not exist for timer.

like image 424
Yifan Avatar asked Aug 29 '16 22:08

Yifan


2 Answers

You should take a look to the Timer operator. You can create an Observable that emits a particular item after a given delay. You can easily create your countdown system.

In this example, I will create a timer and then stop it after 5 seconds.

const start = 20;

const source = Rx.Observable
  .timer(1000, 1000)
  .map(tick => start - tick)
  .take(start + 1)
  .subscribe(tick => console.log(tick));


setTimeout(() => {
  //Stop the timer
  source.unsubscribe();
}, 5000);

You can see the Working plunkr

like image 158
Paul Boutes Avatar answered Oct 02 '22 17:10

Paul Boutes


If unsubscribe does not exist on the result you've received from your call to subscribe, you are likely using RxJS 4. In which case, you will have received an IDisposable instance and should call dispose to stop the timer:

this.timer.dispose();
like image 41
cartant Avatar answered Oct 02 '22 16:10

cartant