Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy/stop observable interval

I have a countdown timer that continues to run after the user has left the page. When the user leaves the page I want to destroy the countdown timer from running or stop it. How can I do this?

countdown.ts

public time: number;
public countDown:Observable<any>;
public currentUnix;

constructor() {
    this.currentUnix = moment().unix();
    this.time = moment(1503773977000).unix() - this.currentUnix;
}


ngOnInit() {
    this.countDown = Observable.interval(1000)
      .map(res => {
        return this.time = this.time - 1
      })
      .map(res => {

        let timeLeft = moment.duration(res, 'seconds');
        let string: string = '';

        // Days.
        if (timeLeft.days() > 0)
          string += timeLeft.days() + ' Days';

        // Hours.
        if (timeLeft.hours() > 0)
          string += ' ' + timeLeft.hours() + ' Hours';

        // Minutes.
        if (timeLeft.minutes() > 0)
          string += ' ' + timeLeft.minutes() + ' Mins';

        // Seconds.
        string += ' ' + timeLeft.seconds();
        console.log("string", string);
        return string;
      })
}
like image 847
derrickrozay Avatar asked Aug 25 '17 19:08

derrickrozay


2 Answers

You can use takeUntil operator.

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';

...

private onDestroy$ = new Subject<void>();

ngOnDestroy(): void {
    this.onDestroy$.next();
}

ngOnInit() {
    this.countDown = Observable.interval(1000)
                               .takeUntil(this.onDestroy$) // <----
                               .map(
... 
like image 59
Aleksandr Petrovskij Avatar answered Sep 28 '22 02:09

Aleksandr Petrovskij


you must have created a subscrtiption based on your this.countDown, you can destroy it in ngOnDestroy,

Excerpt from documentation,

Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive.

....
this.subscription = this.countDown.subscribe(...)
...

public ngOnDestroy() {
    this.subscription.unsubscribe();
}
like image 40
Madhu Ranjan Avatar answered Sep 28 '22 03:09

Madhu Ranjan