RxJS - Transformation Operator buffer



The buffer operates on an observable and takes in argument as an observable. It will start buffering the values emitted on its original observable in an array and will emit the same when the observable taken as argument emits. Once the observable taken as arguments emites the buffer is resets and starts buffering again on original till the input observable emits and the same scenario repeats.

Syntax

buffer(input_observable: Observable): Observable

Parameters

input_observable − an observable that will make the buffer emit values. For example, button click.

Return value

An observable will be returned, that will have an array of buffered values. We will work on an example to understand the working of the buffer() operator.

In the example below, we are going to use a button click as an observable input to buffer. The interval of 1s will be as original observable on which buffer is called. The buffer will collect the clicks passed in the time interval given.

Example

import { fromEvent, interval } from 'rxjs';
import { buffer } from 'rxjs/operators';

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

let btn_clicks = fromEvent(btn, 'click');
let interval_events = interval(1000);
let buffered_array = interval_events.pipe(buffer(btn_clicks));
buffered_array.subscribe(arr => console.log(arr));

Output

buffer Operator
Advertisements