Search code examples
angularrxjssubscriptionangular11

Subscription still live after the parameter changed


I have a subscription to get parameters come with the route and in that subscription(after it success) I am calling another subscription from the same service to get message details. the problem is: when the parameter changed the subscription that related with old parameter still alive.

this.routes.params.subscribe(param => {
        this.isLoading = true;
        this.messageId = param['id'];
        this.inboxService.getMessageDetail(toNumber(this.messageId)).subscribe((dat) => {
          this.initMessageDetails(dat);
        })
      })

Solution

  • This is a perfect use case for the switchMap operator! It subscribes to the child Observable for every emission from the parent, unsubscribing from the previous instance of that child Observable.

    Wherever possible, you should avoid putting logic in your subscribe callbacks, especially if it involves subscribing to another Observable. When using RxJS Observables, use their pipe operator:

    this.routes.params.pipe(
      tap(params => {
        this.isLoading = true;
        this.messageId = params['id'];
      }),
      switchMap(params => this.inboxService.getMessageDetail(toNumber(this.messageId))),
      tap(dat => this.initMessageDetails(dat))
    ).subscribe();
    

    You should also implement some kind of unsubscribe logic to make sure your Observable dies when the component does (using the takeUntil operator and a Subject which emits in ngOnDestroy(), for example).