How do I unsubscribe / stop watching?

I am using the following code for the timer:

export class TimerService {
  private ticks: number = 0;
  private seconds: number = 0;
  private timer;

  constructor(seconds: number) {
    this.seconds = seconds;
    this.timer = Observable.timer(2000, 1000);
    this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks === this.seconds) {
      this.timer.dispose();
    }
  }
}

      

When I try to stop the timer on the line:

this.timer.dispose(); // this.timer.unsubscribe();

      

It doesn't work for me

+3


source to share


2 answers


The method subscribe

returns an object Subscription

that you can later use to stop listening to the stream contained by the observable you are subscribed to.

import { ISubscription } from 'rxjs/Subscription':
import { TimerObservable } from 'rxjs/observable/TimerObservable';

export class TimerService {
  private ticks = 0;
  private timer$: TimerObservable;
  private $timer : ISubscription;

  constructor(private seconds = 0) {
    this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method
    this.$timer = this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks >= this.seconds) {
      this.$timer.unsubscribe();
    }
  }
}

      



It is important to note that it unsubscribe

exists in rxjs (version 5 and higher), before that, in rx (version lower than 5, different package), the method was calleddispose

+8


source


The best way is to unsubscribe when the instance is destroyed.



ngOnDestroy() {
 this.sub.unsubscribe();
}

      

+2


source







All Articles