Angular 8: How to send the http request immediately using interval of Observable

Viewed 661

I have the functionality to send the request from frontend to backend continuosly. so I added the code as given below.

I want to implement in way that the first request should go immediately and then after two minutes.

but with below code and as per definition of interval, it will send the first request after two min.

this.getData = Observable.interval(2 * 60 * 1000)
      .pipe(flatMap(() => this.service.getData(b, b, b, b, b, b))).subscribe();

I dont want to repeat the code by adding a request first and then adding the above code, any other way to accomplish it.

1 Answers

The most trivial way to solve it would be to use timer operator instead of interval operator with an initial delay of 0 seconds.

this.getData = Observable.timer(0, 2 * 60 * 1000)
      .pipe(flatMap(() => this.service.getData(b, b, b, b, b, b))).subscribe();

Update: using repeat and delayWhen operators

The above solution would be useful for simple use-cases. If you however need to dynamically control the delay between each request and complete the polling based on some condition, you could use repeat, delayWhen and takeWhile operators.

let condition = 0;
this.service.getData(b, b, b, b, b, b).pipe(
  take(1),
  delayWhen(_ => condition === 0 ? timer(0) : timer(2 * 60 * 1000)),   // set poll delay
  repeat(),
  takeWhile(_ => condition < 5),        // stop polling when `condition` is 5
  switchMap(response => {
    // do something and update the `condition`
    condition++;
    return of(response);
  })
).subscribe(
  res => console.log(res),
  err => console.log(err),
  () => console.log('complete')
);

You could also use repeatWhen operator to have more refined control on when the request will be repeated.

Related