0

I want to create an Observable-based poller that waits a certain amount of time between the previous request returning and the next request going out.

Here's the code I tried, but this sets a delay between requests going out:

import {timer} from "rxjs";

    this.timer = timer(1, POLLING_INTERVAL)
     .pipe(concatMap(
        (_) => getData()
      )).subscribe((data) => {
        // do something with data     
      });

ilancohen
  • 89
  • 8
  • Possible duplicate of [Polling server after each server response + delay](https://stackoverflow.com/questions/54344923/polling-server-after-each-server-response-delay) – frido Apr 30 '19 at 10:24

2 Answers2

1

timer isn't ideal for this. Rather use repeatWhen with delay.

import { of } from 'rxjs';
import { repeatWhen, delay } from 'rxjs/operators';

getData().pipe(
  repeatWhen(notifications => notifications.pipe(
    delay(POLLING_INTERVAL),
  )),
).subscribe(...);

Live demo: https://stackblitz.com/edit/rxjs-2evzzi

martin
  • 93,354
  • 25
  • 191
  • 226
  • Won't this delay the first request as well? – ilancohen Apr 30 '19 at 08:40
  • No because `repeatWhen` passes all `next` notifications through and captures only `complete` notifications. If `getData()` emits first `next` and then `complete` then `next` won't be delayed. – martin Apr 30 '19 at 08:46
  • Ok, so this works, except that `getData` needs to be called during each poll, and it depends on changed variables in the closure. – ilancohen Apr 30 '19 at 09:31
  • Actually, it doesn't seem to call `getData` more than once at all, so this isn't what I want. – ilancohen Apr 30 '19 at 09:36
  • @ilancohen If you need to call `getData` each time, then try `defer(()=>getData()).pipe(repeatWhen(...))`. Original answer implied that your logic is contained solely inside source observable subscription logic. – kos Apr 30 '19 at 09:51
0

You has to use the creation interval for: https://stackblitz.com/edit/typescript-ohddud?file=index.ts&devtoolsheight=100 Or timer with two parameters: https://stackblitz.com/edit/typescript-h9pzxr?file=index.ts&devtoolsheight=100

I hope you merge request in a correct way.

Victor Shelepen
  • 1,966
  • 2
  • 16
  • 41