DebounceTime & DistinctUntilChanged Operator - RXJS
In this tutorial, we will learn about the DebounceTime & DistinctUntilChanged operator of RXJS.
The main purpose of distinct operators is to prevent subscribers on the next handler to run if the observable emits the same value again.
Most used in Search for making requests after some time once full text is entered to avoid multiple API calls and improve performance
What is DebounceTime & DistinctUntilChanged Operator in RXJS
DebounceTime Operator:
DebounceTIme makes the request after some specified time to avoid multiple API calls
Example:
HTML
----
<input
type="text"
#myInput
class="form-control form-control-lg"
placeholder="Search..."
/>
@ViewChild("myInput", { static: false }) myInput: ElementRef;
const searchTerm = fromEvent<any>(this.myInput.nativeElement, "keyup").pipe(
map((event) => event.target.value),
debounceTime(1000)
);
searchTerm.subscribe((res) => {
console.log(res);
});
The above example will show output after one second of typing.
distinctUntilChanged
DistinctUntillCHanged avoid a request for the same request type for ex if we pass ‘angular’ in req multiple times it will make only one request
distinct until changed operator emits all items that are distinct by comparison (===) from only one previous item
const searchTerm = fromEvent<any>(
this.myInput.nativeElement,
"keyup"
).pipe(
map((event) => event.target.value),
debounceTime(500),
distinctUntilChanged()
);
searchTerm.subscribe((res) => {
console.log(res);
this.reqData2 = res;
});