我们是否需要取消订阅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.
更多推荐
发布评论