bufferCount

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

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

bufferCount - 图1

Examples

Example 1: Collect buffer and emit after specified number of values

( StackBlitz |
jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { bufferCount } from 'rxjs/operators';
  3. //Create an observable that emits a value every second
  4. const source = interval(1000);
  5. //After three values are emitted, pass on as an array of buffered values
  6. const bufferThree = source.pipe(bufferCount(3));
  7. //Print values to console
  8. //ex. output [0,1,2]...[3,4,5]
  9. const subscribe = bufferThree.subscribe(val =>
  10. console.log('Buffered Values:', val)
  11. );
Example 2: Overlapping buffers

( StackBlitz |
jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { bufferCount } from 'rxjs/operators';
  3. //Create an observable that emits a value every second
  4. const source = interval(1000);
  5. /*
  6. bufferCount also takes second argument, when to start the next buffer
  7. for instance, if we have a bufferCount of 3 but second argument (startBufferEvery) of 1:
  8. 1st interval value:
  9. buffer 1: [0]
  10. 2nd interval value:
  11. buffer 1: [0,1]
  12. buffer 2: [1]
  13. 3rd interval value:
  14. buffer 1: [0,1,2] Buffer of 3, emit buffer
  15. buffer 2: [1,2]
  16. buffer 3: [2]
  17. 4th interval value:
  18. buffer 2: [1,2,3] Buffer of 3, emit buffer
  19. buffer 3: [2, 3]
  20. buffer 4: [3]
  21. */
  22. const bufferEveryOne = source.pipe(bufferCount(3, 1));
  23. //Print values to console
  24. const subscribe = bufferEveryOne.subscribe(val =>
  25. console.log('Start Buffer Every 1:', val)
  26. );

Additional Resources


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