Bird
Raised Fist0
Angularframework~10 mins

switchMap for flattening in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - switchMap for flattening
Outer Observable emits value
↓
switchMap receives value
↓
Cancel previous inner Observable if active
↓
Subscribe to new inner Observable
↓
Inner Observable emits values
↓
Emit inner values downstream
↓
Repeat on next outer emission
switchMap listens to an outer Observable, cancels any previous inner Observable, and switches to a new inner Observable, flattening the emissions.
Execution Sample
Angular
outer$.pipe(
  switchMap(value => inner$(value))
).subscribe(result => console.log(result));
This code listens to outer$, switches to a new inner$ Observable for each outer value, and logs inner emissions.
Execution Table
StepOuter Observable EmissionAction by switchMapInner Observable SubscribedInner EmissionOutput Emitted
1ASubscribe to inner$(A)inner$(A)11
2inner$(A) emits 2inner$(A)22
3BCancel inner$(A), subscribe inner$(B)inner$(B)
4inner$(B) emits 10inner$(B)1010
5inner$(B) emits 20inner$(B)2020
6CCancel inner$(B), subscribe inner$(C)inner$(C)
7inner$(C) emits 100inner$(C)100100
8inner$(C) completesinner$(C)
9outer$ completes
💡 outer$ completes and all inner Observables have completed or been cancelled
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 6Final
Current Inner Observablenoneinner$(A)inner$(B)inner$(C)none
Output Emittednone11,21,2,10,201,2,10,20,100
Key Moments - 2 Insights
Why does switchMap cancel the previous inner Observable when a new outer value arrives?
Because switchMap only cares about the latest outer emission, it cancels the previous inner Observable to avoid emitting outdated values, as shown in steps 3 and 6 where previous inner Observables are cancelled.
What happens to inner Observable emissions after switchMap switches to a new inner Observable?
Emissions from the old inner Observable stop being emitted downstream because it was cancelled; only the new inner Observable's emissions are forwarded, as seen in step 3 cancelling inner$(A) and step 6 cancelling inner$(B).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output emitted at step 4?
A2
B10
C20
D100
💡 Hint
Check the 'Output Emitted' column at step 4 in the execution_table.
At which step does switchMap cancel the inner Observable subscribed to inner$(A)?
AStep 3
BStep 5
CStep 2
DStep 6
💡 Hint
Look for the step where the action mentions cancelling inner$(A) in the execution_table.
If the outer Observable emitted a new value after step 8, what would switchMap do?
AEmit the last inner Observable's last value again
BSubscribe to a new inner Observable and cancel any previous one
CIgnore the new value because outer$ completed
DThrow an error
💡 Hint
Recall switchMap behavior from the concept_flow and how it reacts to new outer emissions.
Concept Snapshot
switchMap listens to an outer Observable.
When a new outer value arrives, it cancels the previous inner Observable.
It subscribes to a new inner Observable created from the outer value.
Only emissions from the latest inner Observable are forwarded.
Useful for flattening and switching streams dynamically.
Full Transcript
switchMap is an operator in Angular that listens to an outer Observable. When the outer Observable emits a value, switchMap cancels any previous inner Observable it was subscribed to and subscribes to a new inner Observable created from the latest outer value. This means only the latest inner Observable's emissions are passed downstream. For example, if the outer Observable emits values A, B, and C, switchMap will subscribe to inner$(A), then cancel it when B arrives and subscribe to inner$(B), then cancel inner$(B) when C arrives and subscribe to inner$(C). This behavior helps avoid outdated data and keeps the stream focused on the latest information.

Practice

(1/5)
1. What is the main purpose of switchMap in Angular RxJS?
easy
A. To combine multiple observables into one without canceling
B. To switch to the latest inner observable and cancel previous ones
C. To delay the emission of values by a fixed time
D. To filter values based on a condition

Solution

  1. Step 1: Understand the behavior of switchMap

    switchMap listens to an outer observable and switches to a new inner observable each time the outer emits, canceling the previous inner observable.
  2. Step 2: Compare with other operators

    Unlike operators that combine or delay, switchMap cancels previous inner observables to avoid outdated data.
  3. Final Answer:

    To switch to the latest inner observable and cancel previous ones -> Option B
  4. Quick Check:

    switchMap = switch to latest and cancel old [OK]
Hint: Remember: switchMap cancels old streams, keeps newest only [OK]
Common Mistakes:
  • Confusing switchMap with mergeMap which merges all observables
  • Thinking switchMap delays values instead of switching
  • Assuming switchMap filters values directly
2. Which of the following is the correct syntax to use switchMap in an Angular service?
easy
A. observable$.pipe(switchMap(value => http.get(url)))
B. observable$.switchMap(value => http.get(url))
C. switchMap(observable$, value => http.get(url))
D. observable$.map(switchMap(value => http.get(url)))

Solution

  1. Step 1: Recall RxJS pipe syntax

    In Angular, operators like switchMap are used inside the pipe() method on observables.
  2. Step 2: Check each option

    observable$.pipe(switchMap(value => http.get(url))) correctly uses observable$.pipe(switchMap(...)). observable$.switchMap(value => http.get(url)) is invalid because switchMap is not a method on observable directly. switchMap(observable$, value => http.get(url)) has wrong argument order. observable$.map(switchMap(value => http.get(url))) misuses map.
  3. Final Answer:

    observable$.pipe(switchMap(value => http.get(url))) -> Option A
  4. Quick Check:

    Use pipe() with switchMap inside [OK]
Hint: Use pipe() to chain switchMap, not direct method call [OK]
Common Mistakes:
  • Calling switchMap directly on observable without pipe
  • Mixing switchMap with map incorrectly
  • Passing wrong arguments to switchMap
3. Given the code below, what will be logged to the console?
const source$ = of('A', 'B', 'C');
source$.pipe(
  switchMap(letter => of(letter + '1', letter + '2'))
).subscribe(console.log);
medium
A. "C1" and "C2" only
B. ["A1", "A2", "B1", "B2", "C1", "C2"]
C. "A1" and "A2" only
D. Error: switchMap requires an observable

Solution

  1. Step 1: Understand source observable emissions

    The source$ emits 'A', then 'B', then 'C' synchronously.
  2. Step 2: Apply switchMap to each emission

    For each letter, switchMap maps to an observable emitting letter+'1' and letter+'2'. Since source$ emits synchronously, switchMap cancels previous inner observables when a new outer emission occurs, so only the last inner observable's values "C1" and "C2" are emitted.
  3. Step 3: Resulting output

    Only "C1" and "C2" are logged to the console.
  4. Final Answer:

    "C1" and "C2" only -> Option A
  5. Quick Check:

    switchMap cancels previous inner observables, so only last inner observable outputs [OK]
Hint: switchMap cancels previous inner observables, outputs only latest inner values [OK]
Common Mistakes:
  • Thinking switchMap flattens all inner observables in order
  • Expecting all inner observable outputs
  • Confusing switchMap with mergeMap behavior
4. Identify the error in this Angular RxJS code using switchMap:
this.searchTerm$.switchMap(term => this.http.get(`/api/search?q=${term}`))
  .subscribe(results => this.results = results);
medium
A. subscribe callback syntax is incorrect
B. http.get should be replaced with http.post
C. switchMap is used without pipe()
D. searchTerm$ should be a Subject, not Observable

Solution

  1. Step 1: Check usage of switchMap

    In Angular RxJS, operators like switchMap must be used inside the pipe() method, not called directly on the observable.
  2. Step 2: Verify other parts

    http.get usage is valid for GET requests. subscribe callback syntax is correct. searchTerm$ can be any observable.
  3. Final Answer:

    switchMap is used without pipe() -> Option C
  4. Quick Check:

    Operators need pipe() to work [OK]
Hint: Always use pipe() to apply switchMap on observables [OK]
Common Mistakes:
  • Calling switchMap directly on observable
  • Confusing http.get with http.post
  • Miswriting subscribe callback
5. You want to implement a live search input in Angular that cancels previous HTTP requests when the user types fast. Which RxJS operator should you use and why? searchTerm$.pipe( /* what operator here? */ )
hard
A. mergeMap, because it merges all requests and shows all results
B. exhaustMap, because it ignores new requests while one is active
C. concatMap, because it queues requests and processes them one by one
D. switchMap, because it cancels previous requests and uses only the latest

Solution

  1. Step 1: Understand live search requirements

    Live search needs to cancel previous HTTP requests if the user types again quickly to avoid outdated results.
  2. Step 2: Match operator behavior

    switchMap cancels previous inner observables (HTTP requests) and switches to the latest, perfect for live search. mergeMap merges all requests, concatMap queues them, exhaustMap ignores new while active.
  3. Final Answer:

    switchMap, because it cancels previous requests and uses only the latest -> Option D
  4. Quick Check:

    Live search = switchMap cancels old requests [OK]
Hint: Use switchMap to cancel old HTTP calls on new input [OK]
Common Mistakes:
  • Using mergeMap causing multiple overlapping requests
  • Using concatMap causing delayed responses
  • Using exhaustMap ignoring new inputs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard