MyInternships.in

RxJS & Reactive Programming

Angular Debounce Search with RxJS

A production search box combines four operators: debounceTime to wait for a typing pause, distinctUntilChanged to ignore repeated values, filter to skip very short terms, and switchMap to cancel stale requests.


What is Debounce Search with RxJS in Angular?

A production search box combines four operators: debounceTime to wait for a typing pause, distinctUntilChanged to ignore repeated values, filter to skip very short terms, and switchMap to cancel stale requests.

Debounce Search with RxJS example

The full pipeline
TypeScript
searchControl = new FormControl('');

results$ = this.searchControl.valueChanges.pipe(
  map(v => (v ?? '').trim()),
  debounceTime(400),
  distinctUntilChanged(),
  filter(term => term.length === 0 || term.length >= 2),
  switchMap(term => term ? this.api.search(term) : of([])),
  catchError(() => of([]))
);

How this works

Order matters. Trimming first means trailing spaces do not count as a new term; debouncing before distinctUntilChanged means only settled values are compared; switchMap last guarantees only the newest request survives.

Key points to remember

  • 300–500 ms is the usual debounce window for search.
  • Consume results$ with the async pipe so nothing needs unsubscribing.
  • catchError inside the pipeline keeps a failed request from killing the stream.

Common mistakes with Debounce Search with RxJS

  • Placing catchError outside switchMap, so one failure terminates the whole stream permanently.
  • Forgetting distinctUntilChanged and re-querying when the user retypes the same term.

Angular Debounce Search with RxJS— Interview Questions & FAQs

Why does my search stop working after an error?+

The error propagated to the outer stream and completed it. Put catchError inside the switchMap projection so only that inner request fails, leaving the outer stream alive.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships