1

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));
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Pascal Chorus
  • 360
  • 4
  • 12

2 Answers2

2

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.

Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
2

switchMap does not change anything with regards to unsubscribing.

But the fact that you are combining activatedRoute's streams does. Check out this answer.

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed. There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions. The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79