Search code examples
rxjsreactive-programming

Reactivo Programming Exercise


I have an source observable that emits when you click. I want to make an operator that emits like the next marble diagram ...

That is, it emits when making the first click. Then, it emits when you have 2 items, then it emits when you have 3 items, etc.

Marble diagram

I know that can be done with scan and filter operators, but my question is, if it is possible to do it with the bufferWhen operator?.

I tried to do it (like this), but the result is not what I expected (the first click is not emitted immediately).


Solution

  • It works as follow code. Try avoid reusing source in bufferWhen, there may be race condition

    const source$ = fromEvent(document, 'click').pipe(
      map(_ => new Date())
    );
    
    interval(1000).pipe(
      tap(d => console.log('CLICK:', d)),
      bufferWhen(() => {
        return source$
      })
    ).subscribe(console.log);