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()
}
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With