AI Hints
Home›Angular Tutorial›RxJS Basics, map and filter and Search with debounceTime
Angular · Lesson 102 of 120

Search with debounceTime

Wait for the user.

⏱ 2 min read▶ Video at 2:03:04🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

In module eleven, our search sent a request for nearly every key press. That's wasteful. RxJS can wait until the user stops typing.

  • A request per key
  • Wasteful
  • Wait for a pause

Two search operators

Debounce time waits for a pause, before passing on the latest value. Values that arrive during the wait are dropped. Switch map starts a request for each value. If a new value arrives, it cancels the old request, so old results never win.

keyvalue
debounceTime(300)wait for a 300 ms pause
Droppedvalues during the wait
switchMap(q => req(q))a request per value
Cancelsthe old request

debounceTime

The subject gets each step of typing austen, a hundred milliseconds apart. Debounce time waits for three hundred milliseconds of quiet. Later, we type emma. Run it. Six key presses became one search. Then emma made a second one.

main.tstypescript
import { Subject, debounceTime } from 'rxjs';

const typed$ = new Subject<string>();
typed$.pipe(debounceTime(300)).subscribe(q => console.log('Search for:', q));

const keys = ['a', 'au', 'aus', 'aust', 'auste', 'austen'];
keys.forEach((q, i) => setTimeout(() => typed$.next(q), i * 100));

setTimeout(() => typed$.next('emma'), 1500);
Output
Search for: austen
Search for: emma
Also uses _mode
ts

switchMap

Fake request answers after two hundred milliseconds. We search for aus, then for austen, before aus has answered. Run it. Switch map cancelled the request for aus. Only the results for austen arrived.

main.tstypescript
import { Subject, switchMap, timer, map } from 'rxjs';

const query$ = new Subject<string>();
const fakeRequest = (q: string) => timer(200).pipe(map(() => `results for ${q}`));

query$.pipe(switchMap(q => fakeRequest(q))).subscribe(r => console.log(r));

query$.next('aus');
setTimeout(() => query$.next('austen'), 100);
Output
results for austen
Also uses _mode
ts

Summary

Debounce time waits for the user to pause, and switch map cancels old requests. Together, they make a good search. Next, bringing observables into signals.

Key takeaways
  • debounceTime()
  • switchMap()
  • One search, not six
Next up: toSignal() — observables to signals