rxjs emit only at specific intervals

42 views Asked by At

I would like to call a function only at specific intervals of time, specifically 3 and 6 seconds, and am having some difficulty finding the correct operator to use.

bufferTime seemed like a good candidate, but the array it outputs isn't what I would expect.

Here's a short example:

summarize(): void {
  const responseInterval = interval(1000);
  const responseIntervalObservable = responseInterval.pipe(bufferTime(1000));

  responseIntervalObservable.subscribe(intervalValue => {
    console.log('intervalValue', intervalValue);
  });
}

This outputs:

intervalValue []
intervalValue [0, 1]
intervalValue [2]
intervalValue [3]
intervalValue [4]
intervalValue [5]
intervalValue [6]
intervalValue [7]
intervalValue [8]

I was hoping to see something like [1], [2], [3] so I could call a function specifically at 3 seconds and again at 6 seconds.

What is the correct, or better operator to use?

2

There are 2 answers

0
Brandon Taylor On BEST ANSWER

I ended up just using interval rather than putting bufferTime in-bewteen. That emits a zero-based index for the iteration rather than an array.

Then I can just check the index for a specific value until the request is complete or times out.

1
Get Off My Lawn On

Not sure if this is overkill or not, but you could do something like this.

Our watcher does the following:

  • Filter only 2 and 5 (because it is 0 based)
  • Do something with the value (just log to console in this example)
  • Filter the interval for 5
  • take the first item
  • Cancel the http request (just log to the console for the example)
  • finalize (optional) just to show that this was complete

The http request does the following:

  • Take until the watcher completes (take(1) is called)
const watcher = interval(1000).pipe(
  filter((i) => i === 2 || i === 5),
  tap((i) => console.log(i + 1, 'seconds have passed')),
  filter((i) => i === 5),
  take(1),
  finalize(() => console.log('Watcher Complete'))
);

// An example long running process (such as an http request).
fromFetch('https://example.com')
  .pipe(
    takeUntil(watcher),
    finalize(() => console.log('Http Request Canceled'))
  )
  .subscribe();

Here is an example.