Member-only story

RxJS: When to Use switchMap

Nicholas Jamieson
3 min readMar 13, 2018

--

Photo by Geran de Klerk on Unsplash

In a response to RxJS: Avoiding switchMap-Related Bugs, Martin Hochel mentioned a classic use case for switchMap. For the use case to which he referred, switchMap is not only valid; it’s optimal. And it’s worth looking at why.

Dealing with stale results

Let’s look at an example that involves an expensive call to a backend service: a search for addresses that match a partial address typed into an HTML input.

Here’s the NgRx effect:

And here’s the redux-observable epic:

The effect/epic debounces the user input so that backend searches are not performed for each keystroke and uses distinctUntilChanged so that no searches are performed unless the partial address has changed. The operator that’s then used to flatten the backend observable is switchMap.

--

--

Nicholas Jamieson
Nicholas Jamieson

Written by Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Responses (2)