bluehost-banner
DebounceTime & DistinctUntilChanged Operator - RXJS

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;
    });

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment