Angular Debounce within ValueChanges of form

1.8k views Asked by At

I have a list called filteredUserNames which contains a lot of users. Everytime I change a value on my form it starts a new filter of the data. I know that to delay the time so that not every character triggers a new filter I need to use debounce, but I'm not sure where to add it. Should it be inside the value changes subscription? Also what is the correct way to implement it?

I have

searchString = new BehaviorSubject("");
searchString$ = this.searchString.asObservable();

In Constructor

this.myForm = this.fb.group({
  searchString: [""],
});
this.myForm.controls.searchString.valueChanges.subscribe((val) => {
// SHOULD THE DEBOUNCE GO HERE ?? //  
this.searchString.next(val);  
}

In ngOnInit

this.searchString$.subscribe((searchTerm) => {
      console.log(this.userNames);
      if (this.userNames !== undefined) {
      this.filteredUserNames = this.userNames.filter(
        (userName) =>
          userName.searchTerms
            .toLowerCase()
            .indexOf(searchTerm.toLowerCase()) !== -1
      );
      };
    });
1

There are 1 answers

0
Fateh Mohamed On BEST ANSWER

try this and you can add distinctUntilChanged to ignore similar values and tap operator for your side effects which is in your case emitting a new value to your behaviorSubject

import { tap, distinctUntilChanged, debounceTime} from 'rxjs/operators';
...

this.myForm.controls.searchString.valueChanges.pipe(
   debounceTime(400),
   distinctUntilChanged(),
   tap((val) => this.searchString.next(val))    
 ).subscribe()