Code coverage report for src/operator/sample.ts

Statements: 100% (29 / 29)      Branches: 100% (2 / 2)      Functions: 100% (10 / 10)      Lines: 100% (26 / 26)      Ignored: none     

All files » src/operator/ » sample.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        1 1                         1 16     1 16     1 16   1   1   16   1 16 16     1 42 42     1 22     1 5     1 27 15 15     1  
import {Operator} from '../Operator';
import {Observable} from '../Observable';
import {Subscriber} from '../Subscriber';
 
import {OuterSubscriber} from '../OuterSubscriber';
import {subscribeToResult} from '../util/subscribeToResult';
 
/**
 * Returns an Observable that, when the specified sampler Observable emits an item or completes, it then emits the most
 * recently emitted item (if any) emitted by the source Observable since the previous emission from the sampler
 * Observable.
 *
 * <img src="./img/sample.png" width="100%">
 *
 * @param {Observable} sampler - the Observable to use for sampling the source Observable.
 * @returns {Observable<T>} an Observable that emits the results of sampling the items emitted by this Observable
 * whenever the sampler Observable emits an item or completes.
 */
export function sample<T>(notifier: Observable<any>): Observable<T> {
  return this.lift(new SampleOperator(notifier));
}
 
class SampleOperator<T> implements Operator<T, T> {
  constructor(private notifier: Observable<any>) {
  }
 
  call(subscriber: Subscriber<T>) {
    return new SampleSubscriber(subscriber, this.notifier);
  }
}
 
class SampleSubscriber<T, R> extends OuterSubscriber<T, R> {
  private value: T;
  private hasValue: boolean = false;
 
  constructor(destination: Subscriber<any>, notifier: Observable<any>) {
    super(destination);
    this.add(subscribeToResult(this, notifier));
  }
 
  protected _next(value: T) {
    this.value = value;
    this.hasValue = true;
  }
 
  notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {
    this.emitValue();
  }
 
  notifyComplete(): void {
    this.emitValue();
  }
 
  emitValue() {
    if (this.hasValue) {
      this.hasValue = false;
      this.destination.next(this.value);
    }
  }
}