RxJs switchMap operator

A common mistake made in Angular applications is to nest observable subscriptions in the following manner:

observable1.subscribe(data => {
   observable2.subscribe(otherData => {
     // Do something with otherData
   });
});Code language: JavaScript (javascript)

The above syntax is not recommended because it is hard to read and can lead to subtle bugs and unexpected side effects. For instance, that syntax makes it difficult to unsubscribe properly from all these observables.

Also, if observable1 emits more than once in a short amount of time, we might want to cancel the previous subscription to observable2 and start a new one based on the new data received from observable1. The above code does not do any of that.

The solution: Use the RxJs switchMap operator like so:

observable1.pipe(data => {
   switchMap(data => observable2)
).subscribe(otherData => {
     // Do something with otherData
});Code language: JavaScript (javascript)

The switchMap operator does all of the following:

  • Automatically cancel and unsubscribe from observable2 if observable1 emits a new value.
  • Automatically unsubscribes from observable2 if we unsubscribe from observable1
  • Makes sure that observable1 and observable2 happen in sequence, one after the other.

The following marble diagram is a good illustration of what switchMap does:

If you’re not using switchMap yet, look in your code for nested calls to .subscribe(), and you can start replacing those with the switchMap operator to prevent memory leaks and bugs and make your code more readable.

Here is a link to an example that uses a timer to make HTTP requests every 30 seconds to get updated data. The timer data is turned into an API call using switchMap on line 37 of the example.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.