Code coverage report for src/operator/throttle.ts

Statements: 100% (36 / 36)      Branches: 100% (6 / 6)      Functions: 100% (10 / 10)      Lines: 100% (33 / 33)      Ignored: none     

All files » src/operator/ » throttle.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 1   1 20     1 20     1 20   1   1     1 20 20     1 196 62 62 1   61 61         1 70 70 61 61 61       1 8     1 43   1  
import {Operator} from '../Operator';
import {Observable} from '../Observable';
import {Subscriber} from '../Subscriber';
import {Subscription} from '../Subscription';
 
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {OuterSubscriber} from '../OuterSubscriber';
import {subscribeToResult} from '../util/subscribeToResult';
 
export function throttle<T>(durationSelector: (value: T) => Observable<number> | Promise<number>): Observable<T> {
  return this.lift(new ThrottleOperator(durationSelector));
}
 
class ThrottleOperator<T> implements Operator<T, T> {
  constructor(private durationSelector: (value: T) => Observable<number> | Promise<number>) {
  }
 
  call(subscriber: Subscriber<T>): Subscriber<T> {
    return new ThrottleSubscriber(subscriber, this.durationSelector);
  }
}
 
class ThrottleSubscriber<T, R> extends OuterSubscriber<T, R> {
  private throttled: Subscription;
 
  constructor(destination: Subscriber<any>,
              private durationSelector: (value: T) => Observable<number> | Promise<number>) {
    super(destination);
  }
 
  protected _next(value: T): void {
    if (!this.throttled) {
      const duration = tryCatch(this.durationSelector)(value);
      if (duration === errorObject) {
        this.destination.error(errorObject.e);
      } else {
        this.add(this.throttled = subscribeToResult(this, duration));
        this.destination.next(value);
      }
    }
  }
 
  _unsubscribe() {
    const throttled = this.throttled;
    if (throttled) {
      this.remove(throttled);
      this.throttled = null;
      throttled.unsubscribe();
    }
  }
 
  notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {
    this._unsubscribe();
  }
 
  notifyComplete(): void {
    this._unsubscribe();
  }
}