How to create a RxJS buffer that groups elements in NodeJS but that does not rely on forever running interval?

前端 未结 2 1342
無奈伤痛
無奈伤痛 2020-12-11 21:50

I\'m capturing events from an application using Rx.Observable.fromEvent in a NodeJS. These are sent to another server using request (https://www.npmjs.com/pack

相关标签:
2条回答
  • 2020-12-11 22:09

    You'll probably need to split the stream and use the second part to trigger the first.

    var source = Rx.Observable.fromEvent(eventEmitter, 'log');
    var closer = source.flatMapFirst(Rx.Observable.timer(2000));
    
    source
         .buffer(closer)
         .map(addEventsToRequestOption)
         .flatMap(function(x) { Promise.resolve(request(x)); })
         //I assume this log method returns a function?
         .subscribe(log('Response received'));
    

    source.flatMapFirst(Rx.Observable.timer(2000)) is the important line here. It creates an Observable that generates a timer that will trigger after 2000 ms. When the first event comes in it will kick off the timer. flatMapFirst will ignore subsequent events as long as the timer is running. When the timer finally emits it will trigger the buffer to emit its current buffer and start again.

    See docs on buffer with a boundary Observable

    0 讨论(0)
  • 2020-12-11 22:16

    A proposed implementation, using the delay operator :

    function emits(who){
      return function (x) { console.log([who, "emits"].join(" ") + " " + x + " click(s)");};
    }
    
    var source = Rx.Observable.fromEvent(document.body, 'click');
    console.log("running");
    
    var delayedSource$ = source.delay(1200);
    
    var buffered$ = source
         .buffer(function () { return  delayedSource$;}).map(function(clickBuffer){return clickBuffer.length;})
    
    buffered$.subscribe(emits("buffer"));
    

    jsbin here : http://jsbin.com/wilurivehu/edit?html,js,console,output

    0 讨论(0)
提交回复
热议问题