Search code examples
angularrxjssubscribeunsubscribe

Method containing a Subscribe is called multiple times, should I unsubscribe old subscriptions each time?


I'm building an Angular app with subscriptions. The component is a chat message page where there's a menu of all your chat messages to others and you can click on each person to view the chat messages with that person. Here's one of my functions inside my component

getAllChatMessages() {

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

Now this getAllChatMessages() function is being called every single time the user clicks on a different person they're chatting with. So in this case, the subscribe is being called multiple times over and over again albeit with different this.currentChatId and this.otherUserId. The takeUntil is only there to unsubscribe when the component is destroyed.

What I'm really not clear is whether the old subscribes are still there while another instance of it is instantiated with the next getAllChatMessages() call. Since each subscribe holds a different resource, should I be unsubscribing to the old subscription every time the getAllChatMessages() is called subsequently?

EDIT:

If I do need to clear out old subscriptions, I'm probably looking at something like this? This way on every subsequent call, I'm removing and unsubscribing the subscription from the last call of 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
    });
  }

Solution

  • Yes - you should be unsubscribing if the subscription is no longer needed. An example using the take operator:

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

    You don't need to clean this up on destroy either, since it's already dead after the first emission.