BACK
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"

  1. debounceTime(20) — don't bother the server while the user is typing. A request fires only after a pause.
  2. distinctUntilChanged() — if the value hasn't changed (a character deleted then immediately retyped, say), no repeat request is needed.
  3. 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

  1. In the createTypeahead$ function, add three operators in order inside pipe: debounceTime(20), distinctUntilChanged(), switchMap(query => searchApi(query)).
  2. 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 // TypeScript
CONSOLE · Console output
Hit Run to see the result...