Learn RxJS
Search…
bufferCount

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

Collect emitted values until provided number is fulfilled, emit as array.

Examples

Example 1: Collect buffer and emit after specified number of values
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { bufferCount } from 'rxjs/operators';
4
5
//Create an observable that emits a value every second
6
const source = interval(1000);
7
//After three values are emitted, pass on as an array of buffered values
8
const bufferThree = source.pipe(bufferCount(3));
9
//Print values to console
10
//ex. output [0,1,2]...[3,4,5]
11
const subscribe = bufferThree.subscribe(val =>
12
console.log('Buffered Values:', val)
13
);
Copied!
Example 2: Overlapping buffers
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { bufferCount } from 'rxjs/operators';
4
5
//Create an observable that emits a value every second
6
const source = interval(1000);
7
/*
8
bufferCount also takes second argument, when to start the next buffer
9
for instance, if we have a bufferCount of 3 but second argument (startBufferEvery) of 1:
10
1st interval value:
11
buffer 1: [0]
12
2nd interval value:
13
buffer 1: [0,1]
14
buffer 2: [1]
15
3rd interval value:
16
buffer 1: [0,1,2] Buffer of 3, emit buffer
17
buffer 2: [1,2]
18
buffer 3: [2]
19
4th interval value:
20
buffer 2: [1,2,3] Buffer of 3, emit buffer
21
buffer 3: [2, 3]
22
buffer 4: [3]
23
*/
24
const bufferEveryOne = source.pipe(bufferCount(3, 1));
25
//Print values to console
26
const subscribe = bufferEveryOne.subscribe(val =>
27
console.log('Start Buffer Every 1:', val)
28
);
Copied!
Example 3: Last n keyboard presses tracking
1
// RxJS v6+
2
import { fromEvent, of } from 'rxjs';
3
import { bufferCount, map, mergeMap, tap } from 'rxjs/operators';
4
5
const fakeKeyPressesPost = keypresses =>
6
of(201).pipe(
7
tap(_ => {
8
console.log(`received key presses are: ${keypresses}`);
9
document.getElementById('output').innerText = keypresses;
10
})
11
);
12
13
fromEvent(document, 'keydown')
14
.pipe(
15
map((e: KeyboardEvent) => e.key),
16
bufferCount(5),
17
mergeMap(fakeKeyPressesPost)
18
)
19
.subscribe();
Copied!

Additional Resources

Last modified 2yr ago