buffer

signature: buffer(closingNotifier: Observable): Observable

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

buffer - 图1

Examples

Example 1: Buffer until document click

( StackBlitz |
jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { fromEvent } from 'rxjs/observable/fromEvent';
  3. import { buffer } from 'rxjs/operators';
  4. //Create an observable that emits a value every second
  5. const myInterval = interval(1000);
  6. //Create an observable that emits every time document is clicked
  7. const bufferBy = fromEvent(document, 'click');
  8. /*
  9. 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.
  10. */
  11. const myBufferedInterval = myInterval.pipe(buffer(bufferBy));
  12. //Print values to console
  13. //ex. output: [1,2,3] ... [4,5,6,7,8]
  14. const subscribe = myBufferedInterval.subscribe(val =>
  15. console.log(' Buffered Values:', val)
  16. );

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/buffer.ts