Keith Nicholas Keith Nicholas - 3 months ago 13
Node.js Question

How to do a sliding buffer stream?

Given the following code where I use

bufferCount
(not quite what I want)...

var Rx = require('rxjs/Rx');
var Observable = Rx.Observable;
var Subject = Rx.Subject;

var first = new Rx.Subject();

var source = first.bufferCount(2).map(a => a.reduce((acc,x) => acc+x,0));

var subscription = source.subscribe(console.log)

first.next(1)
first.next(2)
first.next(2)
first.next(3)


I get

3
5


what I'd like to get is

3
4
5


so the buffer is buffering the last 2 items.

Is there a way to do this simply?

Answer

Have you tried using bufferCount's skip / startBufferEvery parameter? This allows you to generate overlapping buffers, which you can then reduce as desired. This way doesn't involve emitting values you have to subsequently filter out. If you specifically want a buffer size of 2, you can use pairwise instead of bufferCount.

Keith:- The code using this method

var Rx = require('rxjs/Rx');
var Observable = Rx.Observable;
var Subject = Rx.Subject;
var R = require('ramda');

var first = new Rx.Subject();

var source = first.bufferCount(2,1).map(a => a.reduce((acc,x) => acc+x,0));

var subscription = source.subscribe(console.log)

first.next(1)
first.next(2)
first.next(2)
first.next(3)