Learn RxJS
Search…
buffer

signature: buffer(closingNotifier: Observable): Observable

Collect output values until provided observable emits, emit as array.

Examples

Example 1: Using buffer to recognize double clicks
1
// RxJS v6+
2
import { fromEvent } from 'rxjs';
3
import { buffer, filter, throttleTime } from 'rxjs/operators';
4
5
// streams
6
const clicks$ = fromEvent(document, 'click');
7
8
/*
9
Collect clicks that occur, after 250ms emit array of clicks
10
*/
11
clicks$
12
.pipe(
13
buffer(clicks$.pipe(throttleTime(250))),
14
// if array is greater than 1, double click occured
15
filter(clickArray => clickArray.length > 1)
16
)
17
.subscribe(() => console.log('Double Click!'));
Copied!
Example 2: Buffer until document click
1
// RxJS v6+
2
import { interval, fromEvent } from 'rxjs';
3
import { buffer } from 'rxjs/operators';
4
5
//Create an observable that emits a value every second
6
const myInterval = interval(1000);
7
//Create an observable that emits every time document is clicked
8
const bufferBy = fromEvent(document, 'click');
9
/*
10
Collect all values emitted by our interval observable until we click document. This will cause the bufferBy Observable to emit a value, satisfying the buffer. Pass us all collected values since last buffer as an array.
11
*/
12
const myBufferedInterval = myInterval.pipe(buffer(bufferBy));
13
//Print values to console
14
//ex. output: [1,2,3] ... [4,5,6,7,8]
15
const subscribe = myBufferedInterval.subscribe(val =>
16
console.log(' Buffered Values:', val)
17
);
Copied!

Additional Resources