setTimeout for only 1 asynchronous call

Issue

How do we use setTimeout for only 1 asynchronous call ? . I wanna set timeout for a purpose before calling the GetData from the dataservice but setTimeout should only be use for only 1 asynchronous call .

Any idea ? thanks.

#html code

 <app-table-multi-sort (dataServiceEvent)="dataServiceEvent($event)"></app-table-multi-sort>

#ts code

dataServiceEvent(item) {
    this.table = item;
    if (this.table) {
      setTimeout(()=>{
        this._GetData()
        },500); 
    }
  }

private GetData() {
    this.isLoading = true;
    this._brokerOpinionOfValueService
      .getAllWAGBOVs(
        this.accountId,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput.nativeElement.value,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe({
        error: (err) => this._notificationService.showError(err),
        next: (res) => {
          
        },
        complete: noop,
      });
  }

Solution

Can be done like :-

getDataSubject: Subject = new Subject();

ngOnInit() {
  this.getDataSubject.pipe(
    scan((acc, curr) => acc + 1, 0),
    mergeMap(count => {
        return iif(() => count < 2, this._GetData().pipe(delay(500)), this.getData())
    })
  ).subscribe();
}

dataServiceEvent(item) {
  this.getDataSubject.next();
}

Answered By – Aakash Garg

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.