Code coverage report for src/operator/throttle.ts

Statements: 100% (55 / 55)      Branches: 100% (8 / 8)      Functions: 100% (15 / 15)      Lines: 100% (50 / 50)      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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85    1 1     1 1 1   1 19     1 19     1 19   1   1     1 19 19     1 188 61 61 61 1 1   60 7   60 60       1 6 6     1 10 10     1 74 74 52 52 52     1   1 60 60     1 9     1 3     1 49   1  
import {Operator} from '../Operator';
import {Observable} from '../Observable';
import {PromiseObservable} from '../observable/fromPromise';
import {Subscriber} from '../Subscriber';
import {Subscription} from '../Subscription';
 
import {tryCatch} from '../util/tryCatch';
import {isPromise} from '../util/isPromise';
import {errorObject} from '../util/errorObject';
 
export function throttle<T>(durationSelector: (value: T) => Observable<any> | Promise<any>): Observable<T> {
  return this.lift(new ThrottleOperator(durationSelector));
}
 
class ThrottleOperator<T, R> implements Operator<T, R> {
  constructor(private durationSelector: (value: T) => Observable<any> | Promise<any>) {
  }
 
  call(subscriber: Subscriber<T>): Subscriber<T> {
    return new ThrottleSubscriber(subscriber, this.durationSelector);
  }
}
 
class ThrottleSubscriber<T> extends Subscriber<T> {
  private throttled: Subscription<any>;
 
  constructor(destination: Subscriber<T>,
              private durationSelector: (value: T) => Observable<any> | Promise<any>) {
    super(destination);
  }
 
  _next(value: T): void {
    if (!this.throttled) {
      const destination = this.destination;
      let duration = tryCatch(this.durationSelector)(value);
      if (duration === errorObject) {
        destination.error(errorObject.e);
        return;
      }
      if (isPromise(duration)) {
        duration = PromiseObservable.create(duration);
      }
      this.add(this.throttled = duration._subscribe(new ThrottleDurationSelectorSubscriber(this)));
      destination.next(value);
    }
  }
 
  _error(err: any): void {
    this.clearThrottle();
    super._error(err);
  }
 
  _complete(): void {
    this.clearThrottle();
    super._complete();
  }
 
  clearThrottle(): void {
    const throttled = this.throttled;
    if (throttled) {
      throttled.unsubscribe();
      this.remove(throttled);
      this.throttled = null;
    }
  }
}
 
class ThrottleDurationSelectorSubscriber<T> extends Subscriber<T> {
  constructor(private parent: ThrottleSubscriber<any>) {
    super(null);
  }
 
  _next(unused: T): void {
    this.parent.clearThrottle();
  }
 
  _error(err): void {
    this.parent.error(err);
  }
 
  _complete(): void {
    this.parent.clearThrottle();
  }
}