Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS: Aggregated debounce

Tags:

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 . 
like image 502
Seba Kerckhof Avatar asked Mar 01 '16 10:03

Seba Kerckhof


1 Answers

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

like image 64
Matt Burnell Avatar answered Oct 05 '22 06:10

Matt Burnell