Lessons49. Project: typeahead search
Lessons · 49
49. Project: typeahead search
Project 1 — a live-search field
This is the first of the "project" lessons. You already know every operator it needs, on its own. The task now is to assemble them into a production typeahead-search pattern.
Three "layers of defense"
debounceTime(20)— don't bother the server while the user is typing. A request fires only after a pause.distinctUntilChanged()— if the value hasn't changed (a character deleted then immediately retyped, say), no repeat request is needed.switchMap(searchApi)— if a new query arrives while the old one is still running, the old one is cancelled.
query$.pipe(
debounceTime(20),
distinctUntilChanged(),
switchMap(q => searchApi(q))
)
Your task
- In the
createTypeahead$function, add three operators in order insidepipe:debounceTime(20),distinctUntilChanged(),switchMap(query => searchApi(query)). - Don't forget the commas!
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, switchMap } = Rx;
function createTypeahead$(query$, searchApi) {
return query$.pipe(
debounceTime(20),
distinctUntilChanged(),
switchMap(query => searchApi(query))
);
} script.ts
CONSOLE · Console output
Hit Run to see the result...