debounceTime to a service call

Viewed 343

I'm trying to send this request using debounceTime method, to not send multiple times to server. but is not working. This service is being called instantly.

On drag'n'drop drop event I want to save positions with saveWidgetsPosition func.

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer !== event.container) {
      transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);
    } else {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    }

    this.saveWidgetsPosition(this.columns);
  }

Function to save positions

saveWidgetsPosition(columns: any[]) {
    const columnsLabels = columns.map(x => x.map(y => y.label));

    this.userService.saveWidgetsPosition({ user: this.user, columns: columnsLabels})
        .pipe(debounceTime(5000))
        .subscribe(res => console.log(res));
}
2 Answers

You're approaching this from the wrong direction. You need to debounce the execution of this.userService.saveWidgetsPosition(). Instead of debouncing processing the results of it.

You could do something like:

widgetPositions = new Subject<any>();
widgetPositions.pipe(
    debounceTime(5000),
    exhaustMap((data) => this.userService.saveWidgetPositions(data))
).subscribe(result => {
    console.log(result);
});

saveWidgetsPosition(columns: any[]) {
    const columnsLabels = columns.map(x => x.map(y => y.label));

    widgetPositions.next({ user: this.user, columns: columnsLabels });
}

debounceTime isn't supposed to do that. Use delay instead.

debounceTime: Discard emitted values that take less than the specified time between output

You are looking for delay.
Your code should be:

this.userService.saveWidgetsPosition({ user: this.user, columns: columnsLabels})
      .pipe(delay(5000))
      .subscribe(res => console.log(res));
Related