Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stop observable.timer in Angular2

I am implementing the following functions in Angular2's 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 repeat of Observable.timer once the value is correctly stored with setFormData().

But do not know how, please tell me.

like image 291
xKxAxKx Avatar asked May 18 '17 05:05

xKxAxKx


People also ask

How do I cancel observable timer?

There're are basically two ways: call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.

How do you stop observable?

takeUntil(notifier) See, we pipe the observable to takeUntil before we subscribe. The takeUntil will emit the values emitted by the interval until the notifier Subject emits, it will then unsubscribe the observable$. The best place to make the notifier to emit so the observable$ is canceled is in the ngOnDestroy hook.


2 Answers

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

like image 132
martin Avatar answered Oct 13 '22 23:10

martin


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(); 
like image 39
Pardeep Jain Avatar answered Oct 14 '22 00:10

Pardeep Jain