Code coverage report for src/operator/buffer.ts

Statements: 100% (24 / 24)      Branches: 100% (0 / 0)      Functions: 100% (8 / 8)      Lines: 100% (21 / 21)      Ignored: none     

All files » src/operator/ » buffer.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53        1 1                             1 20     1   20     1 20   1   1 20   1 20 20     1 45     1 26 26 26   1  
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
 
import {OuterSubscriber} from '../OuterSubscriber';
import {subscribeToResult} from '../util/subscribeToResult';
 
/**
 * Buffers the incoming observable values until the passed `closingNotifier`
 * emits a value, at which point it emits the buffer on the returned observable
 * and starts a new buffer internally, awaiting the next time `closingNotifier`
 * emits.
 *
 * <img src="./img/buffer.png" width="100%">
 *
 * @param {Observable<any>} closingNotifier an Observable that signals the
 * buffer to be emitted} from the returned observable.
 * @returns {Observable<T[]>} an Observable of buffers, which are arrays of
 * values.
 */
export function buffer<T>(closingNotifier: Observable<any>): Observable<T[]> {
  return this.lift(new BufferOperator<T>(closingNotifier));
}
 
class BufferOperator<T> implements Operator<T, T[]> {
 
  constructor(private closingNotifier: Observable<any>) {
  }
 
  call(subscriber: Subscriber<T[]>): Subscriber<T> {
    return new BufferSubscriber(subscriber, this.closingNotifier);
  }
}
 
class BufferSubscriber<T, R> extends OuterSubscriber<T, R> {
  private buffer: T[] = [];
 
  constructor(destination: Subscriber<T[]>, closingNotifier: Observable<any>) {
    super(destination);
    this.add(subscribeToResult(this, closingNotifier));
  }
 
  protected _next(value: T) {
    this.buffer.push(value);
  }
 
  notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {
    const buffer = this.buffer;
    this.buffer = [];
    this.destination.next(buffer);
  }
}