为什么我们需要取消订阅 Observable ?

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 在完成或出错后会 "unsubscribe" 自己。

Do we need to unsubscribe from observable that completes/errors-out?

关于取消订阅 completeerror 通知,您是正确的。

我认为关键是getAuth() method in auth.ts中的评论:

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

因此,您应该订阅 af.auth.subscribe(...),以便在实际 authState 发生变化时收到通知。这意味着它没有完成(类似于 Observable.fromEvent(...)),您必须手动取消订阅。

好吧,不仅 completeerror 事件取消订阅 Observable,而且实际上是 proper way 取消订阅。

如此 post 中所列,完成与取消订阅的优势是:

  • 通常代码较少
  • 更好的分解/设计代码;您的完成规则在一个地方;订阅的开始和结束在同一个地方
  • 你利用 complete 事件编写任何 "completion / clean up" 代码(没有 unsubscribe 事件)

我也得到了作者的回答:

豪尔赫·维加拉

您不需要(取消订阅())。我这样做是因为我只希望 observable 在应用程序启动时将人们发送到那些页面,如果我要让我的用户登录或在 auth 中进行一些更改,我不希望那个观察者启动并将我的用户重定向到某个地方。