Search code examples
rxjsreactivex

RXJS: Aggregated debounce


My use case is as following: I get events, which sometimes happen in bursts. If a burst occurs, I only need to handle it once though. Debounce does this.

However, debounce only gives me the last element of a burst, but I need to know about all elements in a burst to aggregate on them (using flatmap).

This could be done by a timed window or buffer, however, these are fixed intervals, so a buffer/window timeout could occur in the middle of a burst, therefore splitting the burst in 2 parts to handle instead of 1.

So what I'd want is something like

.
.
event: a
.
. -> a
.
.
.
.
.
.event: b
.event: c
.event: d
.
.-> b,c,d
. 
.
.
.
.event : e
.
. -> e
.

Solution

  • This can be achieved with buffer by passing a debounced stream in as a closing selector, e.g.:

    var s = Rx.Observable.of('a')
      .merge(Rx.Observable.of('b').delay(100))
      .merge(Rx.Observable.of('c').delay(150))
      .merge(Rx.Observable.of('d').delay(200))
      .merge(Rx.Observable.of('e').delay(300))
      .share()
    ;
    
    s.buffer(s.debounce(75)).subscribe(x => console.log(x));
    

    Here's a runnable version: https://jsbin.com/wusasi/edit?js,console,output