How to stop observable .timer in Angular2

I implement the following functions in Angular2 Component:

export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } private setFormData() { this.editUserAcountType = this.authStore.registerInfo.account_type; this.editAddress = this.authStore.registerInfo.email; this.editUserName = this.authStore.registerInfo.username; } } 

I want to stop the repetition of Observable.timer after saving the value correctly using setFormData() .

But I don’t know how, please tell me.

+13
javascript angular typescript rxjs rxjs5
source share
2 answers

There are two main ways:

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

To just unsubscribe you can 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 using the takeUntil() statement:

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

See also:

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

January 2019: updated for RxJS 6

+28
source share

you can use the unsubscribe method when you want to stop the observed timer as follows

 this.timer = Observable.timer(100, 100); this.subscription = this.timer.subscribe(t => { this.setFormData(); }); ............. this.subscription.unsubscribe(); 
+4
source share

All Articles