css*_*n25 6 unsubscribe subscribe rxjs angular
我正在构建一个带有订阅的 Angular 应用程序。该组件是一个聊天消息页面,其中有一个菜单,其中包含您向其他人发送的所有聊天消息,您可以单击每个人以查看与该人的聊天消息。这是我的组件内的函数之一
getAllChatMessages() {
this.chatService
.getChatMessages(this.currentChatId, this.otherUserId)
.takeUntil(this.ngUnsubscribe)
.subscribe(userProfile => {
//some logic here
});
}
Run Code Online (Sandbox Code Playgroud)
getAllChatMessages()现在,每次用户单击正在与他们聊天的不同人时,都会调用此函数。因此,在这种情况下,订阅会被一遍又一遍地调用,尽管使用的是不同的this.currentChatId和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
});
}
Run Code Online (Sandbox Code Playgroud)
是的 - 如果不再需要订阅,您应该取消订阅。使用运算符的示例take:
this.chatService
.getChatMessages(this.currentChatId, this.otherUserId).pipe(take(1))
.subscribe(...)
Run Code Online (Sandbox Code Playgroud)
您也不需要在销毁时清理它,因为它在第一次发射后就已经死了。
| 归档时间: |
|
| 查看次数: |
4735 次 |
| 最近记录: |