I wonder if I am using Observable.subscribe() too many times or not.
In my component class, I have a function loadData(). It calls another function this.service.getData() that uses HttpClient.get() to perform a HTTP request to the server.
Currently in my function loadData(), I subscribe to the result of this.service.getData().
Each time the user clicks on a "Update" button, I would like to call my function loadData().
The question
- If I call my function loadData() every time I need to perform HTTP request, will I create as many subscribers?
- Is there a risk of memory leaks?
- If so, do you know how I should refactor my code?
The answer
- I found this other post Is it necessary to unsubscribe from observables created by Http methods?
- It explains that the Angular code actually call observable.complete () after an HTTP request, with a delay
- So I modified my code below to check that fact and the tests confirmed that it was true
Samples of code
private loadData() {
this.loading = true;
const subscription = this.service.getData()
.pipe(
// console.log() with a delay added for test - START
map(val => {
window.setTimeout(() => {
// This will print true.
console.log('After delay: Is Subscriber closed?', subscription.closed);
}, 10);
return val;
}),
// console.log() with a delay added for test - END
takeUntil(this.ngUnsubscribe))
.subscribe(data => {
this.data = data;
// This will print false.
console.log('Is Subscriber closed?', subscription.closed);
},
error => {
console.error(error);
throw error;
},
() => {
this.loading = false;
});
}
getData(): Observable<DataObject> {
const uri = encodeURI(this.configService.getUri());
const headers = new HttpHeaders();
if (this.pipelineEtag) {
headers.set('If-None-Match', this.pipelineEtag);
}
return this.http.get(uri, {
headers: headers,
observe: 'response'
}).pipe(
map(resp => this.processResponse(resp)),
catchError(error => this.handleError(error, this.envProduction))
);
}