Lessons21. Search: debounceTime + distinctUntilChanged
Lessons · 21
21. Search: debounceTime + distinctUntilChanged
The classic search combination
This is the course's first practical "recipe." On its own, neither of the two "guards" handles live search:
- Without
debounceTime, a request flies off on every keystroke. - Without
distinctUntilChanged, retyping the same text (after clearing and typing it again, say) fires a redundant request.
Why this order
You usually put debounceTime before distinctUntilChanged. The logic: first "settle" the stream (drop the intermediate values during fast typing), then compare the stable value against the previous stable one.
input$.pipe(
debounceTime(30),
distinctUntilChanged()
)
Your task
- In the
createQuery$function, insidepipe, putdebounceTime(30)first, thendistinctUntilChanged()after a comma. - The marble simulates the input
ang → angular, thenangularagain (a duplicate, which should be dropped), thenrxjs. - Expected output: only
angularandrxjs.
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 { debounceTime, distinctUntilChanged } = Rx;
function createQuery$(input$) {
return input$.pipe(
debounceTime(30),
distinctUntilChanged()
);
} script.ts
CONSOLE · Console output
Hit Run to see the result...