How to Stop observable.timer in Angular2

There’re are basically two ways:

  • call unsubscribe() on the Subscription object returned from the subscribe() call .
  • use an operator

To just unsubscribe you could do it like this.

ngOnInit() {
  this.subscription = timer(100, 100).subscribe(t => {
    this.setFormData();
  });
}

private setFormData() {
  ...
  this.subscription.unsubscribe();
}

Or you can use Subject to complete the Observable via takeUntil() operator:

this.subject = new Subject();

ngOnInit() {
  timer(100, 100).pipe(
    takeUntil(this.subject),
  ).subscribe(t => this.setFormData());
}

private setFormData() {
  ...
  this.subject.next();
}

Have a look these as well:

  • Difference between .unsubscribe to .take(1)
  • RxJS: takeUntil() Angular component’s ngOnDestroy()

Jan 2019: Updated for RxJS 6

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)