Search code examples
javascriptfrpbacon.js

Bacon.js control buffering of stream with other stream


I want to buffer values of an EventStream in Bacon.js exactly like buffer(closingSelector) behaves in RxJava. When the "controller stream" (closingSelector in RxJava method) emits a new value, then the event buffer gets flushed.

So I want that the stream output is similar as in stream.bufferWithTimeOrCount, but instead of controlling buffering with time interval or event count I want to control buffering with other stream.

Is there an easy way to implement this in Bacon.js?


Solution

  • Bacon.js didn't have the function as you needed it, so I looked at the bacon.js source and wrote a modified version of holdWhen.

    Bacon.EventStream.prototype.bufferUntilValue = function(valve) {
    var valve_ = valve.startWith(false);
    
      return this.filter(false).merge(valve_.flatMapConcat((function(_this) {
        return function() {
            return _this.scan([], (function(xs, x) {
                return xs.concat(x);
            }), {
                eager: true
            }).sampledBy(valve).take(1);
        };
      })(this)));
    };
    

    To see this in action, check out this jsFiddle.