Within a component, I have implemented a form that needs to perform two actions when the values are changed:
- Immediately update the view
- Emit the form values to the parent component after a brief delay
The parent component contains a service tasked with making API requests upon changes in the form values. To avoid sending a request with every keystroke and thus reducing unnecessary calls, I decided to throttle the event emission.
The challenge now is managing the two separate subscribers: one for updating the view and another employing debounceTime
to handle the EventEmitter
:
private subscribeToChanges(): void {
this.form.valueChanges.pipe(
distinctUntilChanged(),
takeUntil(this.isDestroyed$)
).subscribe(() => {
this.updateView();
});
this.form.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
takeUntil(this.isDestroyed$)
).subscribe(() => {
this.changed.emit(this.form.value);
});
}
In attempting to find a more elegant solution, I briefly considered adding a timeout within the initial subscriber, but it didn't feel quite right.
What would be the most appropriate approach to handling this situation?