wait for all pending request resolved and take value from last

江枫思渺然 提交于 2019-12-11 04:23:28

问题


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)">

回答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.




回答2:


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




回答3:


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);
   }
 }


来源:https://stackoverflow.com/questions/53408051/wait-for-all-pending-request-resolved-and-take-value-from-last

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!