我们是否需要取消订阅完成/出错的 observable? [英] Do we need to unsubscribe from observable that completes/errors-out?
问题描述
当我知道 observable 肯定会完成(带有 complete
或 error
通知)之前我的组件/类退出范围,我是否仍然需要取消订阅以防止内存泄漏?换句话说,是否自动清理了已完成/错误的 observable,所以我不必担心?
When I know that the observable will definitely complete (either with complete
or an error
notification) before my component/class goes out of scope, do I still need to unsubscribe from it to prevent memory leaks? In other words, is completed/error-ed observable cleaned-up automagically so I don't have to worry?
推荐答案
订阅和取消订阅部分rel="noreferrer">Observable Contract 对您的问题是明确的.它指出:
The Subscribing and Unsubscribing section of the Observable Contract is definitive regarding your question. It states:
当 Observable 向其观察者发出 OnError 或 OnComplete 通知时,订阅将结束.以这种方式被 Observable 终止的订阅,Observer 不需要发出 Unsubscribe 通知.
When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end subscriptions that are ended by the Observable in this way.
这也在Observable Termination部分提到:
当 Observable 向其观察者发出 OnError 或 OnComplete 通知时,订阅将结束.
When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription.
所以,不,没有必要取消订阅完成或出错的 observable.但是,这样做并没有什么坏处.
So, no, there is no need to unsubscribe from observables that complete or error. However, there is no harm in doing so.
这篇关于我们是否需要取消订阅完成/出错的 observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!