RxJS - Transformation Operator bufferCount



In the case of buffercount operator, it will collect the values from the observable on which it is called and emit the same when the buffer size given to buffercount matches. It takes 2 arguments buffersize and the second one is startBufferEvery i.e. it will count the new values from startBufferEvery if given or else from the beginning of the source observable.

Syntax

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

Parameters

bufferSize − The size of the buffer to be emitted.

Return value

An observable will be returned, that will have an array of buffered values.

We will see a working example of bufferCount()

Example 1

import { fromEvent } from 'rxjs';
import { bufferCount } from 'rxjs/operators';

let btn = document.getElementById("btnclick");

let btn_clicks = fromEvent(btn, 'click');
let buffered_array = btn_clicks.pipe(bufferCount(4));
buffered_array.subscribe(arr => console.log(arr));

In the above example, the bufferSize is 4. So, after a count of 4 clicks the array of click events is collected in an array and displayed. Since we have not given the startBufferEvery the values will be counted from the start.

Output

bufferCount Operator

Example 2

import { fromEvent } from 'rxjs';
import { bufferCount } from 'rxjs/operators';

let btn = document.getElementById("btnclick");
let btn_clicks = fromEvent(btn, 'click');
let buffered_array = btn_clicks.pipe(bufferCount(4, 2));
buffered_array.subscribe(arr => console.log(arr));

In this example, we have added startBufferEvery, so after every 2 clicks, it will display a buffer count of 4 click events.

Output

bufferCount Ex Operator
Advertisements