为什么我们需要取消订阅Observerable?(how come we need to unsubscribe from an Observerable ?)

编程入门 行业动态 更新时间:2024-10-27 18:30:48
为什么我们需要取消订阅Observerable?(how come we need to unsubscribe from an Observerable ?)

我们是否需要取消订阅Observable? 我们什么时候需要使用取消订阅?

我阅读了一篇关于使用firebase.auth检查用户登录状态的angularfire2文章。 在代码的最后,他取消了auth.subscribe的订阅。 https://javebratt.com/angularfire2-email-auth/ (请参阅app.component.ts)。

我真的很困惑,因为我认为Observable将在完成或出错后“取消订阅”。

我们是否需要取消订阅完成/错误输出的可观察对象? 你需要取消订阅Angular 2 http调用以防止内存泄漏吗?

Do we ever need to unsubscribe from an Observable? When is the time we need to use unsubscribe?

I read an angularfire2 article talking about using firebase.auth to check user's login status. In the end of code, he unsubscribes from auth.subscribe. https://javebratt.com/angularfire2-email-auth/ (please see app.component.ts).

I was really confused, since I thought the Observable will "unsubscribe" itself after completed or on error.

Do we need to unsubscribe from observable that completes/errors-out? and Do you need to unsubscribe from Angular 2 http calls to prevent memory leak?

最满意答案

关于取消订阅complete或error通知,您是正确的。

我认为关键是getAuth()中getAuth()方法中的auth.ts :

请通过订阅auth服务异步观察实际的authState:af.auth.subscribe()

因此,您应该使用af.auth.subscribe(...)进行订阅, af.auth.subscribe(...)在实际的authState更改时收到通知。 这意味着它没有完成(类似于Observable.fromEvent(...) ),你必须手动取消订阅。

You're correct about unsubscribing on complete or error notification.

I think the key is the comment in getAuth() method in auth.ts:

Please observe the actual authState asynchronously by subscribing to the auth service: af.auth.subscribe()

So you should subscribe with af.auth.subscribe(...) to be notified when the actual authState changes. This means that it doesn't complete (similarly to Observable.fromEvent(...)) and you have to unsubscribe manually.

更多推荐

本文发布于:2023-08-04 08:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1413187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Observerable   unsubscribe

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!