Learn RxJS
Search…
bufferToggle

signature: bufferToggle(openings: Observable, closingSelector: Function): Observable

Toggle on to catch emitted values from source, toggle off to emit buffered values as array.

Examples

Example 1: Toggle buffer on and off at interval
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { bufferToggle } from 'rxjs/operators';
4
5
//emit value every second
6
const sourceInterval = interval(1000);
7
//start first buffer after 5s, and every 5s after
8
const startInterval = interval(5000);
9
//emit value after 3s, closing corresponding buffer
10
const closingInterval = val => {
11
console.log(`Value ${val} emitted, starting buffer! Closing in 3s!`);
12
return interval(3000);
13
};
14
//every 5s a new buffer will start, collecting emitted values for 3s then emitting buffered values
15
const bufferToggleInterval = sourceInterval.pipe(
16
bufferToggle(startInterval, closingInterval)
17
);
18
//log to console
19
//ex. emitted buffers [4,5,6]...[9,10,11]
20
const subscribe = bufferToggleInterval.subscribe(val =>
21
console.log('Emitted Buffer:', val)
22
);
Copied!
Example 2: Toggle buffer on and off on mouse down/up
1
import { fromEvent } from 'rxjs';
2
import { bufferToggle } from 'rxjs/operators';
3
4
fromEvent(document, 'mousemove')
5
.pipe(
6
bufferToggle(fromEvent(document, 'mousedown'), _ =>
7
fromEvent(document, 'mouseup')
8
)
9
)
10
.subscribe(console.log);
Copied!

Additional Resources

Last modified 1yr ago