I have an angular component where I request values from a service periodically:
setInterval(() => {
this.updateValues();
}, 1000);
updateValues(): void {
if (this.isValuesUpdateRunning === false) {
this.isValuesUpdateRunning = true;
this.apiService.getCurrentValues().subscribe((data: any) => {
if (data != null) {
this.currentValues = data;
this.isValuesUpdateRunning = false;
}
});
}
}
I'm pretty sure that I should unsubscribe from the service somewhere because I do open a lot of subscriptions by doing this. I was thinking about using async pipe, but I need to set the "isValueUpdateRunning" variable and that wouldn't be possible if I did just use async within the template.
Also, unsubscribing within the "onDestroy" method provided by Angular doesn't help either because as far as I understand, this method only gets called when I leave the page. But I need to close my subscriptions more often to prevent keeping thousands of subscriptions open.
I also tried closing the subscription immediately after setting my values, but then I'm not getting any values within my view:
updateValues(): void {
if (this.isValuesUpdateRunning === false) {
this.isValuesUpdateRunning = true;
const sub = this.apiService.getCurrentValues().subscribe((data: any) => {
if (data != null) {
this.currentValues = data;
this.isValuesUpdateRunning = false;
}
});
// closing the subscription right here:
sub.unsubscribe();
}
}
Can you help please? I'm running out of ideas.
this.apiService.getCurrentValues()is making an http request with the AngularHttpClient, you don't need to unsubscribe. - Kurt Hamilton