🎯 The Situation
You have a source Observable that emits events (like button clicks or search text).
For each event, you need to start a new inner Observable (like an HTTP call).
These operators decide how to subscribe to those inner Observables.
1️⃣ mergeMap
“Start all inner Observables in parallel and merge their results as they come.”
-
Does NOT cancel previous inner Observables.
-
Fast because everything runs concurrently.
-
Good for: Fire-and-forget tasks, multiple HTTP calls where order doesn’t matter.
➡ If you click 3 times quickly, 3 requests run at the same time, and you get responses in whatever order they arrive.
2️⃣ switchMap
“Switch to the latest inner Observable and cancel the old one.”
-
Cancels previous request when a new value comes in.
-
Good for: Live search/autocomplete, where you only care about the newest result.
➡ If user types “a”, then “ab”, then “abc”, only the request for “abc” is kept. Older ones are aborted.
3️⃣ concatMap
“Queue inner Observables and run them one after another, in order.”
-
Ensures order is preserved.
-
Each inner Observable must finish before the next starts.
-
Good for: Operations that must be sequential (like saving data step by step).
➡ If 3 tasks come quickly, they run one at a time, in the same order.
4️⃣ (Bonus) exhaustMap
“Ignore new values until the current inner Observable finishes.”
-
Useful when you want to block re-entry, e.g., ignore extra button clicks while a request is in progress.
➡ Click many times fast → only the first click triggers a request until it completes.
🔑 Comparison Table
Operator | Starts New? | Cancels Old? | Runs in Parallel? | Keeps Order? | Common Use Case |
---|---|---|---|---|---|
mergeMap | ✅ | ❌ | ✅ | ❌ | Multiple independent calls |
switchMap | ✅ | ✅ | ⚠️ only latest | ❌ | Type-ahead search |
concatMap | ✅ | ❌ | ❌ (sequential) | ✅ | Save tasks in sequence |
exhaustMap | ❌ (while active) | — | ❌ | N/A | Prevent double submits |
🏁 Quick Rules of Thumb
-
Need all results, order unimportant → mergeMap
-
Only care about the latest event → switchMap
-
Must keep order, one at a time → concatMap
-
Ignore new events until done → exhaustMap
These patterns help you choose the right operator when dealing with streams that trigger async work like HTTP requests or long-running tasks.
No comments:
Post a Comment