Do you need to unsubscribe from Angular 2 http calls to prevent memory leak?
fetchFilm(index) {
var sub = this._http.get(`http://example.com`)
.map(result => result.json())
.map(json => {
dispatch(this.receiveFilm(json));
})
.subscribe(e=>sub.unsubscribe());
...
So the answer is no, you don't. Ng2
will clean it up itself.
The Http service source, from Angular's Http XHR backend source:
Notice how it runs the complete()
after getting the result. This means it actually unsubscribes on completion. So you don't need to do it yourself.
Here is a test to validate:
fetchFilms() {
return (dispatch) => {
dispatch(this.requestFilms());
let observer = this._http.get(`${BASE_URL}`)
.map(result => result.json())
.map(json => {
dispatch(this.receiveFilms(json.results));
dispatch(this.receiveNumberOfFilms(json.count));
console.log("2 isUnsubscribed",observer.isUnsubscribed);
window.setTimeout(() => {
console.log("3 isUnsubscribed",observer.isUnsubscribed);
},10);
})
.subscribe();
console.log("1 isUnsubscribed",observer.isUnsubscribed);
};
}
As expected, you can see that it is always unsubscribed automatically after getting the result and finishing with the observable operators. This happens on a timeout (#3) so we can check the status of the observable when it's all done and completed.
And the result
So, no leak would exist as Ng2
auto unsubscribes!
Nice to mention: This Observable
is categorized as finite
, on contrary to the infinite
Observable
which is an infinite stream of data can be emitted like DOM click
listener for example.
THANKS, @rubyboy for help on this.