Flattening Operators
You'll learn how to handle observables that emit other observables using mergeMap, switchMap, and concatMap.
The Problem: Nested Observables
Sometimes an observable emits values that themselves need to be turned into observables. For example, each user click might trigger an HTTP request (which returns an observable). Without flattening, you'd have an "observable of observables"—a nested structure that's hard to work with.
Flattening operators automatically subscribe to these inner observables and flatten the results into a single stream.
The Three Flattening Strategies
mergeMap
Subscribes to all inner observables concurrently. Like opening multiple browser tabs at once—all requests run in parallel, and results arrive in whatever order they complete.
Use when: Order doesn't matter and you want maximum concurrency (e.g., logging analytics events).
switchMap
Cancels the previous inner observable when a new one arrives. Like typing in a search box—each keystroke cancels the previous search request and starts a new one.
Use when: Only the latest result matters (e.g., autocomplete, live search).
concatMap
Waits for each inner observable to complete before subscribing to the next. Like a single-file queue—one request finishes completely before the next begins.
Use when: Order must be preserved and operations shouldn't overlap (e.g., sequential API calls that depend on each other).
The Analogy
Think of a bakery taking orders (outer observable). Each order requires baking (inner observable):
- mergeMap: Multiple ovens baking simultaneously
- switchMap: One oven, but you throw away the current batch when a new order arrives
- concatMap: One oven, completing each batch before starting the next
Key Takeaway: Use mergeMap for concurrent operations, switchMap when only the latest matters, and concatMap when order and completion are critical.