首页 文章

包含订阅的方法被多次调用,我应该每次取消订阅旧订阅吗?

提问于
浏览
0

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

getAllChatMessages() {

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

现在,每当用户点击他们正在聊天的其他人时,就会调用此函数 . 所以在这种情况下,订阅被反复调用多次,尽管有不同的 this.currentChatIdthis.otherUserId . takeUntil 仅在组件被销毁时取消订阅 .

我真正不清楚的是旧订阅是否仍在那里,而另一个实例是在下一个 getAllChatMessages() 调用时实例化的 . 由于每个订阅持有不同的资源,每次 getAllChatMessages() 随后调用时,我是否应取消订阅旧订阅?

EDIT:

如果我确实需要清除旧订阅,我会删除和取消订阅最后一次调用 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
    });
  }

1 回答

  • 1

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

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

    你不需要在破坏时清理它,因为它在第一次发射后已经死了 .

相关问题