【问题标题】:Method containing a Subscribe is called multiple times, should I unsubscribe old subscriptions each time?包含订阅的方法被多次调用,我应该每次都取消订阅旧订阅吗?
【发布时间】:2018-09-07 19:08:09
【问题描述】:

我正在构建一个带有订阅的 Angular 应用程序。该组件是一个聊天消息页面,其中有一个包含您与他人的所有聊天消息的菜单,您可以单击每个人以查看与该人的聊天消息。这是我的组件中的一个函数

getAllChatMessages() {

  this.chatService
    .getChatMessages(this.currentChatId, this.otherUserId)
    .takeUntil(this.ngUnsubscribe)
    .subscribe(userProfile => {
      //some logic here
    });
}

现在,每次用户单击正在与之聊天的其他人时,都会调用此 getAllChatMessages() 函数。所以在这种情况下,订阅被一遍又一遍地调用,尽管this.currentChatIdthis.otherUserId 不同。 takeUntil 只有在组件被销毁时才能取消订阅。

我真正不清楚的是旧订阅是否仍然存在,而它的另一个实例在下一个 getAllChatMessages() 调用中被实例化。由于每个订阅都拥有不同的资源,我是否应该在每次随后调用 getAllChatMessages() 时取消订阅旧订阅?

编辑:

如果我确实需要清除旧订阅,我可能正在寻找类似的东西?这样,在随后的每次通话中,我都会从 getAllChatMessages() 的最后一次通话中删除和取消订阅。

getAllChatMessages() {
  if (this.getChatMsgSub) {
    this.getChatMsgSub.unsubscribe();
  }

  this.getChatMsgSub = this.chatService
    .getChatMessages(this.currentChatId, this.otherUserId)
    .takeUntil(this.ngUnsubscribe)
    .subscribe(userProfile => {
      //some logic here
    });
  }

【问题讨论】:

    标签: angular rxjs subscribe unsubscribe


    【解决方案1】:

    是的 - 如果不再需要订阅,您应该取消订阅。使用take 运算符的示例:

    this.chatService
      .getChatMessages(this.currentChatId, this.otherUserId).pipe(take(1))
      .subscribe(...)
    

    你也不需要在销毁时清理它,因为它在第一次发射后就已经死了。

    【讨论】:

    • 感谢您的回答!在这种情况下,我不想做take(1),因为我确实希望持续订阅流(即,如果用户留在这个聊天室并且有更多聊天消息通过)。请参阅我更新的问题。
    • 您是否也编辑了代码?看起来正确 - 您正在将订阅缓存为 getChatMsgSub 并取消订阅。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2015-10-05
    • 2018-10-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多