是否有必要取消订阅由 Http 方法创建的 observable? [英] Is it necessary to unsubscribe from observables created by Http methods?
问题描述
您是否需要取消订阅 Angular 2 http 调用以防止内存泄漏?
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());
...
推荐答案
所以答案是否定的,您不需要.Ng2
会自行清理.
So the answer is no, you don't. Ng2
will clean it up itself.
Http 服务源,来自 Angular 的 Http XHR 后端源:
The Http service source, from Angular's Http XHR backend source:
注意它在获得结果后如何运行complete()
.这意味着它实际上在完成时取消订阅.所以你不需要自己做.
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.
这是一个验证测试:
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);
};
}
正如预期的那样,您可以看到它总是在获取结果并完成可观察操作符后自动取消订阅.这发生在超时 (#3) 时,因此我们可以在所有完成和完成后检查 observable 的状态.
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.
结果
因此,当 Ng2
自动取消订阅时,不会存在泄漏!
So, no leak would exist as Ng2
auto unsubscribes!
很高兴提到:这个 Observable
被归类为 finite
,与 infinite
Observable
相反,它是例如,可以像 DOM click
侦听器一样发出无限的数据流.
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.
感谢@rubyboy 对此的帮助.
THANKS, @rubyboy for help on this.
这篇关于是否有必要取消订阅由 Http 方法创建的 observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!