bufferTime

signature: bufferTime(bufferTimeSpan: number, bufferCreationInterval: number, scheduler: Scheduler): Observable

Collect emitted values until provided time has passed, emit as array.

Examples

Example 1: Buffer for 2 seconds

( StackBlitz | jsBin |
jsFiddle )

  1. //Create an observable that emits a value every 500ms
  2. const source = Rx.Observable.interval(500);
  3. //After 2 seconds have passed, emit buffered values as an array
  4. const example = source.bufferTime(2000);
  5. //Print values to console
  6. //ex. output [0,1,2]...[3,4,5,6]
  7. const subscribe = example.subscribe(val =>
  8. console.log('Buffered with Time:', val)
  9. );
Example 2: Multiple active buffers

( StackBlitz | jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { bufferTime } from 'rxjs/operators';
  3. //Create an observable that emits a value every 500ms
  4. const source = interval(500);
  5. /*
  6. bufferTime also takes second argument, when to start the next buffer (time in ms)
  7. for instance, if we have a bufferTime of 2 seconds but second argument (bufferCreationInterval) of 1 second:
  8. ex. output: [0,1,2]...[1,2,3,4,5]...[3,4,5,6,7]
  9. */
  10. const example = source.pipe(bufferTime(2000, 1000));
  11. //Print values to console
  12. const subscribe = example.subscribe(val =>
  13. console.log('Start Buffer Every 1s:', val)
  14. );

Additional Resources


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