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

标签 angular rxjs subscribe unsubscribe

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

getAllChatMessages() {

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

现在这个 getAllChatMessages()每次用户单击与他们聊天的不同人时,都会调用该函数。因此,在这种情况下,尽管使用不同的 this.currentChatId 多次调用 subscribe 。和 this.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
    });
  }

最佳答案

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

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

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

关于angular - 多次调用包含订阅的方法,我应该每次都取消订阅旧订阅吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49545663/

相关文章:

angular - 将数组中的值附加到 BehaviorSubject

knockout.js - 在 Knockout.js 中订阅 observableArray 中的可观察属性

angular - combineLatest 与 FormControl valueChanges 事件绑定(bind)不发出

angular - 使用 glob 定位任何具有特定前缀的嵌套文件夹

javascript - 向可观察的响应添加附加参数

Angular CanDeactivate Guard : How to wait for the right or the next value of an Obersavble?

angular - 以 Angular 订阅后如何执行某些操作

angular - 在子 Angular2 中访问父级的变量

angular - Ionic 3 - 过滤复杂数组

angular - 错误 TS2304 : Cannot find name 'ga'