Ibrahim Ali
Ibrahim Ali

Reputation: 2503

how to unsubscribe nested observable | Angular

Depending on the URL param, i am subscribing to an observable (_getData).

  ngOnInit(): void {
    this._subscription.add(
      this.route.queryParamMap.subscribe((params) => { this._getData(params.get('name')).subscribe() })
    );
  }

  ngOnDestroy(): void {
    this._subscription.unsubscribe();
  }

Now every time the param changes, I am subscribing to a new observable (_getData).. So how do i unsubscribe the previous observable?

Upvotes: 0

Views: 634

Answers (2)

Mrk Sef
Mrk Sef

Reputation: 8022

You can use switchMap to manage your subscriptions for you. In this case, every time there are new params, the old this._getData is unsubscribed and a new this._getData is subscribed for you.

ngOnInit(): void {
  this.route.queryParamMap.pipe(
    switchMap(params => this._getData(params.get('name')))
  ).subscribe();
}

Upvotes: 1

dom.macs
dom.macs

Reputation: 796

You can use mergeMap to flatten the inner observable which is the this._getData()

In the code below, I didn't subscribe to your second observable and instead used mergeMap. I did this so that there is only 1 child subscription and will be unsubscribed by the parent this._subscription when you unsubscribe from it.

this._subscription.add(
  this.route.queryParamMap.pipe(
    mergeMap((params) => {
      return this._getData(params.get('name'))
    })
  ).subscribe()
);

Upvotes: 2

Related Questions