Yifan
Yifan

Reputation: 376

How to stop an Observable interval manually?

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.

Upvotes: 5

Views: 14190

Answers (2)

cartant
cartant

Reputation: 58400

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();

Upvotes: 4

Paul Boutes
Paul Boutes

Reputation: 3315

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

Upvotes: 7

Related Questions