All you need to know about the bufferCount operator in RxJS

Satyapriya Mishra
2 min readAug 22, 2020

Buffers the source Observable values until the size hits the maximum bufferSize provided. It also takes an optional parameter called startBufferEvery which is the value interval of creating a new buffer.

Signature

bufferCount(bufferSize: number, startBufferEvery: number = null): OperatorFunction

Buffers a number of values from the source Observable by bufferSize then emits the buffer and clears it, and starts a new buffer each startBufferEvery values.

If startBufferEvery is not provided or is null, then new buffers are started immediately at the start of the source and when each buffer closes and is emitted.

A sample code snippet for the bufferCount operator is given below.

const source = of( 1 , 2 , 3 , 4 , 5 ); // (1)const buffered = source.pipe(bufferCount( 2 , 2 )); // (2)buffered.subscribe(val => console.log(val));

In step1, we create an observable with the of operator which eits values from the provided values sequentially. In the next step we pass that observable to the bufferCount operator with the maximum size as 2 and the startBufferEvery as 2. Next we subscribe to it.

The output of the above code snippet will be

// [1, 2]// [3, 4]// [5]

As we see due to the parameters we passed to the bufferCount operator the output comes in this format. The parameters can be tweaked in different ways to get different outputs.

--

--