switchMap helps you handle changing data streams by switching to the latest one and ignoring old ones. It keeps your app fast and up-to-date without confusion.
switchMap for flattening in Angular
sourceObservable.pipe( switchMap(value => innerObservable) )
switchMap takes a function that returns a new observable.
It unsubscribes from the previous inner observable when a new value arrives.
this.searchInput.valueChanges.pipe( switchMap(term => this.api.search(term)) )
of(1, 2, 3).pipe( switchMap(x => of(x * 10)) ).subscribe(console.log);
This Angular component uses switchMap to handle user input changes. When you type in the input box, it calls fakeApi which simulates a delayed response. If you type quickly, previous calls are cancelled and only the latest result shows.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; import { of } from 'rxjs'; import { delay, switchMap } from 'rxjs/operators'; @Component({ selector: 'app-switchmap-example', template: ` <input [formControl]="searchControl" placeholder="Type to search" aria-label="Search input" /> <p>Result: {{ result }}</p> `, standalone: true }) export class SwitchMapExampleComponent { searchControl = new FormControl(''); result = ''; constructor() { this.searchControl.valueChanges.pipe( switchMap(term => this.fakeApi(term)) ).subscribe(res => this.result = res); } fakeApi(term: string | null) { // Simulate API delay return of(`Result for "${term}"`).pipe(delay(500)); } }
Use switchMap when you want to ignore old inner observables and only keep the latest.
It helps prevent race conditions in asynchronous calls like HTTP requests.
Remember to handle empty or invalid inputs to avoid unnecessary calls.
switchMap switches to the newest inner observable and cancels previous ones.
It is great for handling fast-changing data like user input or live searches.
Helps keep your app responsive and avoids outdated data showing.
Practice
switchMap in Angular RxJS?Solution
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.Step 2: Compare with other operators
Unlike operators that combine or delay, switchMap cancels previous inner observables to avoid outdated data.Final Answer:
To switch to the latest inner observable and cancel previous ones -> Option BQuick Check:
switchMap = switch to latest and cancel old [OK]
- Confusing switchMap with mergeMap which merges all observables
- Thinking switchMap delays values instead of switching
- Assuming switchMap filters values directly
switchMap in an Angular service?Solution
Step 1: Recall RxJS pipe syntax
In Angular, operators like switchMap are used inside thepipe()method on observables.Step 2: Check each option
observable$.pipe(switchMap(value => http.get(url))) correctly usesobservable$.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.Final Answer:
observable$.pipe(switchMap(value => http.get(url))) -> Option AQuick Check:
Use pipe() with switchMap inside [OK]
- Calling switchMap directly on observable without pipe
- Mixing switchMap with map incorrectly
- Passing wrong arguments to switchMap
const source$ = of('A', 'B', 'C');
source$.pipe(
switchMap(letter => of(letter + '1', letter + '2'))
).subscribe(console.log);Solution
Step 1: Understand source observable emissions
The source$ emits 'A', then 'B', then 'C' synchronously.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.Step 3: Resulting output
Only "C1" and "C2" are logged to the console.Final Answer:
"C1" and "C2" only -> Option AQuick Check:
switchMap cancels previous inner observables, so only last inner observable outputs [OK]
- Thinking switchMap flattens all inner observables in order
- Expecting all inner observable outputs
- Confusing switchMap with mergeMap behavior
switchMap:
this.searchTerm$.switchMap(term => this.http.get(`/api/search?q=${term}`))
.subscribe(results => this.results = results);Solution
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.Step 2: Verify other parts
http.get usage is valid for GET requests. subscribe callback syntax is correct. searchTerm$ can be any observable.Final Answer:
switchMap is used without pipe() -> Option CQuick Check:
Operators need pipe() to work [OK]
- Calling switchMap directly on observable
- Confusing http.get with http.post
- Miswriting subscribe callback
searchTerm$.pipe( /* what operator here? */ )Solution
Step 1: Understand live search requirements
Live search needs to cancel previous HTTP requests if the user types again quickly to avoid outdated results.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.Final Answer:
switchMap, because it cancels previous requests and uses only the latest -> Option DQuick Check:
Live search = switchMap cancels old requests [OK]
- Using mergeMap causing multiple overlapping requests
- Using concatMap causing delayed responses
- Using exhaustMap ignoring new inputs
Ready to prove it?
Pass the test and this pattern moves unknown
