Home > Software engineering >  Add delay using rxjs before executing a function
Add delay using rxjs before executing a function

Time:08-05

I have a subscription and need to run a function ( getDetails() ) after getting values from that subscription . But need a delay before calling that function. Currently I used setTimeout() event. But I need to convert it to rxjs way. Any suggestion to do it better way using rxjs?

this.dataQueryService
  .queryOneTable(request)
  .pipe(pluck('items'), take(1))
  .subscribe((data: any[]) => {

    //data handling logic

    setTimeout(() => {
      this.getDetails();
    }, 200);
  });

Update: I need a delay after handling data inside body.

CodePudding user response:

In addition to @BizzyBob answer, you can do it with map.

this.dataQueryService
  .queryOneTable(request)
  .pipe(
    pluck('items'),
    take(1),
    map((data: any[]) => {

      //data handling logic

      return handledData;
    }),
    delay(200)
  )
  .subscribe((handledData: any[]) => {
      this.getDetails();
  });

CodePudding user response:

You could use delay:

this.dataQueryService.queryOneTable(request).pipe(
  pluck('items'), 
  take(1),
  delay(200)
)
.subscribe((data: any[]) => {
  this.getDetails();
});
  • Related