switchMap is usually used when you have some async operation that is triggered by some prepended “event/stream”.
The difference to e.g. flatMap or concatMap is, that as soon as the next trigger emits, the current async operation is canceled and re-triggered.
In your case this means, that as soon as the route-params change, your hero-service is automatically called again with the changed params and the previous call is canceled so you won’t receive outdated data.
This is especially helpful for search-queries that might take longer then 200-300ms and are triggered while a user is typing.
The following code would not be the same?
No. While it might behave the same in many cases, if you imagine the following scenario:
- param changes to “4”
getHero(4)(a very slow request)- param changes to “1”
getHero(1)(a fast request)getHero(1)completes -> hero is “1”getHero(4)completes -> hero is now “4” but the last used param was “1”
In such a case switchMap would just discard the getHero(4)-call since it is outdated as soon as a new trigger happens.