1

I have a method getData() inside Angular app which calls on click every time when asc > desc sorting in the table is changed. If I click it 10 times in a row I will make 10 get request and data will assign to table every time when the request is resolved, so it makes it blinking till the last request. How can I waiting for data only for the last request and ignore another?

 this.getData() {
   this.endpointsService.getData(reqParams).pipe(
      takeUntil(this.ngUnsubscribe$)  
   ).subscribe((data) => {
      this.data$.next(data);
   }
 }

data$ is using in view with *ngFor

*ngFor="let item of (data$ | async)">
Bogdan Tushevskyi
  • 712
  • 2
  • 12
  • 25

3 Answers3

1

The point is not calling directly getData() yourself but rather creating a Subject and stuffing search queries there. You can then use the Subject to create a chain that can unsubscribe from the previous requests:

private s$ = new Subject();
private result$ = s$.pipe(
  takeUntil(this.ngUnsubscribe$),
  switchMap(reqParams => this.endpointsService.getData(reqParams)),
);

getData(reqParams) {
  this.s$.next(reqParams);
}

Then in your template:

*ngFor="let item of (result$ | async)">

The switchMap operator will unsubscribe from its inner Observable on every emission from its source.

Ideally you can also use debounceTime() before switchMap to avoid even creating so many request.

martin
  • 93,354
  • 25
  • 191
  • 226
0

If I understand correctly you want to wait a certain period of time after a user interaction for the table to not change sorting and then apply the function?

You could do so with debounceTime()

 this.getData() {
   this.endpointsService.getData(reqParams).pipe(
      takeUntil(this.ngUnsubscribe$),
      debounceTime(1000), 
      distinctUntilChanged()
   ).subscribe((data) => {
      this.data$.next(data);
   }
 }

debounceTime(1000) will wait for the sorting to be unchanged for 1 second, then it will fetch data

Reference: https://stackoverflow.com/a/50740491/4091337

Teun van der Wijst
  • 939
  • 1
  • 7
  • 21
  • in this situation, debounceTime(1000) is not affected to the server request, because the request will fire and only after it debounceTime, or I'm wrong? – Bogdan Tushevskyi Nov 21 '18 at 08:49
  • Here is an explanation of debounceTime: https://medium.com/aviabird/rxjs-reducing-number-of-api-calls-to-your-server-using-debouncetime-d71c209a4613. Yes the `getData` call will only be executed if debounceTime allows so – Teun van der Wijst Nov 21 '18 at 08:51
  • Yes, but it seems that I need to use debounceTime before the call to api. – Bogdan Tushevskyi Nov 21 '18 at 08:57
0

You can achieve this using Delay operator.

endpointsService:

getData(){
  return this.http.get(url).pipe(
    delay(500)
  )
}

Component:

this.getData() {
   this.endpointsService.getData(reqParams).pipe(
      takeUntil(this.ngUnsubscribe$)
   ).subscribe((data) => {
      this.data$.next(data);
   }
 }
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27