debounce a function inside angular

461 views Asked by At

I would like to add debounce for an argument inside a function

I am having issue because Angular debounce only works for pipe and observable, so I use lodash debounce instead.

whenever the clarity datagrid table refresh, it will call onRefreshTable function and pass the event object which has table filter and sorting state.

Since refreshTable() will call API which takes longer time, I would like to minimize the API call.

Sometimes table refresh is being called multiple times with the same argument, or different argument. If different argument, the last table refresh call will contain all of the needed argument to pass to the API.

My atttempt where no error in the code, but it still call the function few times after 1 second with the same argument,

import * as _ from lodash;
onRefreshTable(event: ClrDatagridStateInterface<any>) {
        _.debounce((event) => {
            this.refreshTable(event)
        }, 1000);     
}
refreshTable(event) {
   // save state to the rxjs store 
   // call API which is expensive
}

I am thinking of using distinctUntilChanged, however it doesn't seems to work for this case, as the argument inside the function is not observable .

Maybe I should use _.cloneDeep instead to compare previous arguments vs current arguments?

1

There are 1 answers

0
g-wei xia On BEST ANSWER

You can use distinctUntilChanged(_.isEqual), and if you have a reference value to compare, passing***.next(JSON.parse(JSON.stringify(customerSearchInfo)))like this.

Code sinppet:

  customerSearchQuery = new Subject<CustomerQueryInfo>();
  customerSearchQuery$ = this.customerSearchQuery.pipe(
    map(queryInfo => {
      queryInfo.keyWord = queryInfo.keyWord.trim();
      return queryInfo;
    }),
    debounce(queryInfo => {
      if (queryInfo.skip > 1 || queryInfo.keyWord === '') {
        return interval(0);
      }
      return interval(800);
    }),
    distinctUntilChanged(_.isEqual),
    switchMap(queryInfo => this.scmContext.BA_Customers.GetPage(queryInfo).Execute())
  );