I have a service. This contains the following function (simplified):
private _eventListener$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
push(field?: FormField): void {
this.isAlive = true;
this._eventListener$.pipe(
debounceTime(3500),
takeWhile(() => this.isAlive)
).subscribe(() => {
this.isAlive = false;
console.log(field?.control.value)
});
}
This function does the following: if a field changes (input, dropdown,...) then the backend should be called and data should be queried. This should not happen directly with every change of a field but only after a certain time nothing has changed. Therefore I have thought, I use debounceTime. But unfortunately this does not work.
If I enter a lot of numbers and I am above the debounce time, all the numbers I enter are logged:
I thought debounceTime always only outputs the last value after nothing has happened for a certain time. Why does this not work?
When something is changed in your component this.formService.push(this.field);
is called. This created a new observable (and subscription) on each change. You should just call this function one time (e.g. in your constructor) and only one value will be emitted. Please remember to unsubscribe on destruction or, even better, don't subscribe at all and use an declarative approach using rxjs
operators + async
pipe.