angularrxjssubscriptionhttpserviceswitchmap

Does switchMap to Angular HTTP-Request needs unsubscribe


I am wondering if I have to unsubscribe my subscription in the following case. I create an observable using combineLatest of the two angular observables route.params and route.queryParams. To use them as parameters within an http request I call switchMap and return the http request's observable. Then I describe to this observable.

Now I am wondering if I have to take care of the subscription. Usually I do not since the observable returned by angular's http service completes after first value emit.

In my current case I am not sure since the original observable was created by calling combineLatest.

// Somewhere within my component.

const subscription = combineLatest(this.route.params, this.route.queryParams).pipe(
  switchMap(([params, queryParams]: [Params, Params]) => this.http.get<number>(`query/path/${params.id}/${queryParams.type}`)
).subscribe(data => console.log(data));

Solution

  • Yes you will need to unsubscribe. This hasn't anything to do with your switch map, but with your combineLatests and its parameters.

    combineLastest will emit the lastest value of each observerable. Both this.route.params and this.route.queryParams will keep emitting values as your route changes. Therefore also your combineLatest will keep emitting values.