DEV Community

Cover image for RxJS Operators: bufferCount
Steven Boyd-Thompson
Steven Boyd-Thompson

Posted on • Originally published at drownedintech.dev

RxJS Operators: bufferCount

RxJS is a JavaScript library that enables the creation of asynchronous and event-based programs. The main type is the Observable and a suite of functions and operators are provided to make it easier to work with the data coming through. This series will detail those operators (and a few stand-alone functions) and provide examples of their use.

In this post, we’re going to cover the bufferCount operator.

What does it do?

The bufferCount operator is used to batch a certain number of values together. When we add bufferCount to our pipeline we pass it a number that indicates the number of values to batch. Once enough values have been received, bufferCount will combine all values into an array and send them through the pipeline.

Example

import { bufferCount, interval } from 'rxjs';

interval(1000)
    .pipe(bufferCount(10))
    .subscribe(x => {
        console.log(x);
    });
Enter fullscreen mode Exit fullscreen mode

We’re using interval to provide us with incrementing numbers every second. When we add bufferCount we’re telling it to wait for 10 values, so every time it receives 10 from interval an array will be sent down the pipeline. Running this will print:

[
  0, 1, 2, 3, 4,
  5, 6, 7, 8, 9
]
[
  10, 11, 12, 13, 14,
  15, 16, 17, 18, 19
]
Enter fullscreen mode Exit fullscreen mode

If the original observable completes the buffer will send whatever values it has collected through the pipeline immediately.

The source code for this example is available on GitHub:

Top comments (0)