How to Stop observable.timer in Angular2

有些话、适合烂在心里 提交于 2019-11-30 17:09:51

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:

Jan 2019: Updated for RxJS 6

you can use unsubscribe method when you want to stop timer observable like this

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

.............
this.subscription.unsubscribe();

A nuance which previous answers haven't really covered is that there is no need to stop an observable timer/interval - at least not by interacting with the observable or the timer itself.

I found myself here because I was setting up an observable using a timer in a HostedService's start method, and in the stop method it seemed like I should be stopping it, or disposing of something surely? - well... no. The observable timer does not need to be stopped or disposed in this way, only the subscriptions, and this is why...

Observable timers and intervals are examples of cold streams (though they appear to behave as hot). They are passive not active, they do not produce data till subscribed to, and stop producing data when no subscribers. Therefore, disposal of all subscriptions should be all that's required to stop the timer producing data.

More info here... [http://introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!