March 13, 2018

To Switchmap Or Not To Switchmap

What the map

When we want to use a flattening operator you usually come across switchMap but this is not the only map operator we have. We have a total of 4 maps to choose from:

  • mergeMap (or flatMap which is an alias)
  • concatMap
  • switchMap
  • exhaustMap

mergeMap/flatMap

This will concurrently handle each dispacthed request, this means it will not wait for any other request to complete and also doesn’t abort the previous one if a new request is fired. This might be a good choice if you don’t mind the order in which the requests complete.

concatMap

This is the same as using the mergeMap but then feeding it one request at a time. Process all requests but one request at a time. If you are unsure about which map to choose this is always a save pick.

switchMap

This will make sure only one request is going through and will cancel the previous observable and created a new one. If you are not concerned about the return value or completion this is the map for you!

exhaustMap

This is the opposite of switchMap, it will ignore the new request if there is already one pending. So it will wait for the first request to finish and will ignore any new ones.

Sources

© Ellen Langelaar 2018