Lessons25. switchMap: the latest request wins
Lessons · 25
25. switchMap: the latest request wins
switchMap — the latest wins
switchMap behaves differently: when a new outer value arrives, it cancels the current inner Observable (if it's still running) and starts a new one.
inputs: 'a' → 'an' → 'angular'
switchMap: request(a) → cancel → request(an) → cancel → request(angular) → result
The headline scenario — typeahead
A user types in a search box. Each intermediate request (for "a", "an") is already obsolete — only the last one matters. switchMap gives you "cancel the stale requests" for free, which is especially valuable for HTTP in Angular.
A recap of the four operators
- mergeMap — parallel, order doesn't matter.
- concatMap — a queue, strict order.
- switchMap — cancel the old, keep the new.
- exhaustMap (next lesson) — ignore the new while the old is running.
Your task
- In
pipe, addswitchMap(value => timer(50).pipe(map(() => 'Done ' + value))). - The source emits
0, 1, 2every 20ms, but the inner timer lasts 50ms. So while0is still counting,1arrives — and the old one is cancelled. - Only the last value,
2, makes it through to a result.
Deterministic check
This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.
Solution spoiler · click to reveal
const { timer, switchMap, map } = Rx;
const source$ = hot('a 19ms b 19ms c|', {
a: 0,
b: 1,
c: 2,
});
const result$ = source$.pipe(
switchMap(value => {
return timer(50).pipe(
map(() => 'Done ' + value)
);
})
); script.ts
CONSOLE · Console output
Hit Run to see the result...