Code coverage report for src/operator/buffer.ts

Statements: 100% (43 / 43)      Branches: 100% (2 / 2)      Functions: 100% (15 / 15)      Lines: 100% (38 / 38)      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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  1                     1 19     1   19     1 19   1   1 19 19   1 19 19 19     1 41     1 7     1 8     1 24 24 24   24 1     1   1 19 19     1 24     1 3     1 4   1  
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
 
/**
 * 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
 *
 * @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(closingNotifier));
}
 
class BufferOperator<T, R> implements Operator<T, R> {
 
  constructor(private closingNotifier: Observable<any>) {
  }
 
  call(subscriber: Subscriber<T>): Subscriber<T> {
    return new BufferSubscriber(subscriber, this.closingNotifier);
  }
}
 
class BufferSubscriber<T> extends Subscriber<T> {
  private buffer: T[] = [];
  private notifierSubscriber: BufferClosingNotifierSubscriber<any> = null;
 
  constructor(destination: Subscriber<T>, closingNotifier: Observable<any>) {
    super(destination);
    this.notifierSubscriber = new BufferClosingNotifierSubscriber(this);
    this.add(closingNotifier._subscribe(this.notifierSubscriber));
  }
 
  _next(value: T) {
    this.buffer.push(value);
  }
 
  _error(err: any) {
    this.destination.error(err);
  }
 
  _complete() {
    this.destination.complete();
  }
 
  flushBuffer() {
    const buffer = this.buffer;
    this.buffer = [];
    this.destination.next(buffer);
 
    if (this.isUnsubscribed) {
      this.notifierSubscriber.unsubscribe();
    }
  }
}
 
class BufferClosingNotifierSubscriber<T> extends Subscriber<T> {
  constructor(private parent: BufferSubscriber<any>) {
    super(null);
  }
 
  _next(value: T) {
    this.parent.flushBuffer();
  }
 
  _error(err: any) {
    this.parent.error(err);
  }
 
  _complete() {
    this.parent.complete();
  }
}