是否需要退订Http方法创建的可观察对象? [英] 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.
这是一个可以验证的测试:
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);
};
}
按预期,您可以看到在获得结果并完成可观察到的运算符后,它总是自动取消订阅.这是在超时(#3)上发生的,因此我们可以检查可观察对象全部完成和完成的状态.
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方法创建的可观察对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!