24 Jul 2024
2 min

switchMap – RxJS Reference

switchMap

switchMap operator is basically a combination of two operators – switchAll and map. The map part lets you map a value from a higher-order source observable to an inner observable stream. The switch part than works like switchAll – it subscribes to the most recently provided inner observable emitted by higher-order observable, unsubscribing from any previously subscribed inner observable.

switchMap has only one active subscription at a time from which the values are passed down to an observer. Once the higher-order observable emits a new value, switchMap executes the function to get a new inner observable stream and switches the streams. It unsubscribes from the current stream and subscribes to the new inner observable.

The operator works in the following way:

  1. Subscribe to a higher-order source observable
  2. When a new value arrives from a source observable, execute a map function that returns an inner observable
  3. Subscribe to this inner observable
  4. When a new value arrives from this inner observable, pass it down to an observer
  5. When a new value arrives from a source observable, execute a map function that returns an inner observable
  6. Unsubscribe from the current inner observable, subscribe to the new inner observable
  7. Only after all source observables complete, send the complete notification to the observer.
  8. If any of the inner source observables throws an error, send the error notification to the observer.

Please note that switchAll will never complete if some of the input streams don’t complete.

Usage

Sometimes receiving values from all inner observable sequences is not what we need. In some scenarios, we may only be interested in the the values from the most recent inner sequence. A good example of such functionality is search. As a user types in some text, the request is sent to a server and since it’s asynchronous the result is returned as an observable. What if the user updates the text in the search-box before the result is returned? The second request is sent and so by now two searches have been sent to the server. However, the first search contains the results that we are no longer interested in. Furthermore, if the result for the first search was merged together with result for the second search, the user would be very surprised. We don’t want that and so this is where switchAll operator comes in. It subscribes and produces values only from the most recent inner sequence ignoring previous streams.

Here’s an example of using switchMap to switch between two streams:

const urls = [
   'https://api.mocki.io/v1/0350b5d5',
   'https://api.mocki.io/v1/ce5f60e2'
];

from(urls).pipe(
   switchMap((url) => {
       return fromFetch(url);
   })
).subscribe((response) => console.log(response.status));

Playground

Additional resources

See also

Frequently asked questions

How does switchMap work in RxJS?

switchMap combines map and switchAll: it maps each value from the source observable to an inner observable, then subscribes only to the most recent inner observable and unsubscribes from the previous one. Only one inner subscription is active at a time, so values from earlier inner streams are ignored. The operator completes only after the source and the active inner observable complete, and any inner error is forwarded to the observer.

When should I use switchMap instead of mergeMap in RxJS?

Use switchMap when only the result of the most recent inner observable matters, such as a search box where an older request's results would be stale. Use mergeMap when values from all inner observables should be kept, because mergeMap subscribes to every inner observable concurrently. With switchMap, a new source value cancels the previous inner subscription, so earlier responses that arrive late are never emitted.

How do I implement a search-as-you-type request with switchMap in Angular?

Pipe the input's value stream through switchMap and map each query to an observable request, such as fromFetch() or an HttpClient call. When the user types again before the previous response arrives, switchMap unsubscribes from the earlier request and subscribes to the new one. This prevents outdated search results from being displayed and avoids merging responses for different queries together.

Why does switchMap never complete in my RxJS stream?

switchMap only sends the complete notification after all source observables have completed. If the source or the currently active inner observable never completes, the resulting stream stays open. For example, a long-lived inner stream like an interval or a subject will keep switchMap from completing. To finish the stream, make sure the source and inner observables complete, or add an operator such as take() or takeUntil().

What is the difference between switchMap and switchAll in RxJS?

switchAll subscribes to the latest higher-order observable emitted by the source and unsubscribes from the previous one, but it does not transform values. switchMap is essentially switchAll combined with map, so it takes each source value, runs a projection function to create the inner observable, and then switches to it. Use switchMap when each source value must be converted into a new request or stream.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.