BACK
Use casesTypeahead — search with suggestions
Use cases · 01

Typeahead — search with suggestions

Pattern

Typeahead is a search field that sends a request to the server as the user types. Without RxJS this UI quickly turns into a race: the user has typed 7 letters, the server returns responses to 7 different requests in arbitrary order, and someone else's results flicker in the dropdown.

What we solve

  • Input jitter. While the user types fast, we don't hit the server on every letter.
  • Repeats. If the value hasn't changed (pasting the same text, backspace/redo), no request is needed.
  • Response race. When a new request comes in, the old one should be cancelled.

The operators and their roles

  • debounceTime(300) — wait for a pause in typing.
  • distinctUntilChanged() — ignore consecutive repeated values.
  • switchMap — for each new request we unsubscribe from the previous one, cancelling it.

What we achieve

One HTTP request per stable value, an always-current response in the UI, and no manual unsubscription.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...