Lessons26. exhaustMap: ignore while busy
Lessons · 26
26. exhaustMap: ignore while busy
exhaustMap — busy, come back later
exhaustMap is the opposite of switchMap. It starts the first inner task and ignores every new outer value until that task finishes. Once it's done, it's ready to accept the next value again.
The headline scenario
A Login or Submit button. The user gets antsy and clicks four times in a row. We want only one request to go out — the repeat clicks are ignored.
Compared with switchMap
switchMap: "I'll take the latest" — cancels the old
exhaustMap: "I'm busy, back off" — ignores the new
Your task
- In
pipe, addexhaustMap(value => timer(20).pipe(map(() => 'Processed ' + value))). - The marble simulates clicks 0, 1, 2 close together, then a pause, then 3.
- Expected output:
Processed 0(the first click), thenProcessed 3(a new click after the pause). Clicks 1 and 2 are ignored — we were "busy."
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, exhaustMap, map } = Rx;
const clicks$ = hot('a 5ms b 5ms c 30ms d|', {
a: 0,
b: 1,
c: 2,
d: 3,
});
const result$ = clicks$.pipe(
exhaustMap(value => {
return timer(20).pipe(
map(() => 'Processed ' + value)
);
})
); script.ts
CONSOLE · Console output
Hit Run to see the result...