2
votes

I have this sample code:

interval(500).pipe(
  throttleTime(1000)
).subscribe(arg => {
  console.log(arg);
});

Which emits:

0
3
6
...

I understand that it emits the latest value every 1000 milliseconds. My problem is that it ignores the values that aren't the latest. Is there an operator similar to throttleTime, but one that saves these ignored values? I'd like it to emit:

[0]
[1,2,3]
[4,5,6]
...

Edit: Ideally, I'd like something that listens to clicks of a button. When the first click happens, the code starts a timer for N milliseconds. The user can keep clicking during this time. Once N milliseconds are up, the operator fires with an array holding all of the events that happened during those N milliseconds.

Super-ideally, I'd like the timer to reset everytime the user clicks the button.

1

1 Answers

2
votes

You can use bufferToggle. It collects values and returns in an array, just as per your requirement:

const click$ = fromEvent(document, 'click').pipe(
  // count emitions
  scan(acc => acc += 1, 0)
)

const timerInterval = () => timer(5000);

// buffer emitions to an array. When first click happens 'turn on' buffer
// and when timer ends turn it off. 
// throttle used to avoid turning on buffer on every click  

click$.pipe(
  bufferToggle(
    click$.pipe(throttle(timerInterval)),
    timerInterval
  ),
)
.subscribe(console.log)

But to note - there is no clear separation between clicking intervals. For ex., user might be clicking longer than 5 secs and in result, two emitions will happen.

But this is more as an architectural task for you to solve.

DEMO