Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: How to unsubscribe rsjx interval or timer?

I think the question is clear. I coudn't find any informations about how to unsubscribe from a rsjx-operation like interval or timer?

My Component:

public intervallTimer = interval(5000);

ngOnInit() {
  this.getValues();
  this.intervallTimer.subscribe(() => this.getValues());
}

// What I like to do is something like this, but "unsubscribe()" that's no function
somefunction(){
  this.intervallTimer.unsubscribe()
}
like image 311
Max Avatar asked Dec 10 '22 05:12

Max


2 Answers

subscribe returns a Subscription object that has unsubscribe as a method. One option that you have is:

public intervallTimer = interval(5000);
private subscription;

ngOnInit() {
  this.getValues();
  this.subscription = this.intervallTimer.subscribe(() => this.getValues());
}

somefunction(){
  this.subscription.unsubscribe()
}

This requires you to explicitly unsubscribe from subscriptions, which you may not want to do. You could also consider using takeUntil, which returns a complete Observable that will cause an automatic unsubscribe. Just make sure that takeUntil is the last in any chain.

public intervallTimer = interval(5000);
private alive = true;

ngOnInit() {
  this.getValues();
  this.intervallTimer.pipe(takeUntil(() => !this.alive)).subscribe(() => this.getValues());
}

somefunction(){
  this.alive = false;
}
like image 162
Ian MacDonald Avatar answered Dec 12 '22 17:12

Ian MacDonald


Or you can use takeWhile(Boolean) to control the behaviour

this.intervallTimer.pipe(
      takeWhile(// your condition)
).subscribe(() => this.getValues()); 

you can find the documentation from here

like image 25
Jayampathy Wijesena Avatar answered Dec 12 '22 18:12

Jayampathy Wijesena