b8ce6a7c1fcdbf426ccb6718dd14d49294745b61d2f9ec73ecd6e693646f4b49605205fb3eab418bfe76efce08bb2ce9ae2b956c7b53ebeea0d5ba2030b815 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { Operator } from '../Operator';
  2. import { Observable } from '../Observable';
  3. import { Subscriber } from '../Subscriber';
  4. import { Subscription } from '../Subscription';
  5. import { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';
  6. import { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';
  7. export interface ThrottleConfig {
  8. leading?: boolean;
  9. trailing?: boolean;
  10. }
  11. export const defaultThrottleConfig: ThrottleConfig = {
  12. leading: true,
  13. trailing: false
  14. };
  15. /**
  16. * Emits a value from the source Observable, then ignores subsequent source
  17. * values for a duration determined by another Observable, then repeats this
  18. * process.
  19. *
  20. * <span class="informal">It's like {@link throttleTime}, but the silencing
  21. * duration is determined by a second Observable.</span>
  22. *
  23. * ![](throttle.png)
  24. *
  25. * `throttle` emits the source Observable values on the output Observable
  26. * when its internal timer is disabled, and ignores source values when the timer
  27. * is enabled. Initially, the timer is disabled. As soon as the first source
  28. * value arrives, it is forwarded to the output Observable, and then the timer
  29. * is enabled by calling the `durationSelector` function with the source value,
  30. * which returns the "duration" Observable. When the duration Observable emits a
  31. * value or completes, the timer is disabled, and this process repeats for the
  32. * next source value.
  33. *
  34. * ## Example
  35. * Emit clicks at a rate of at most one click per second
  36. * ```ts
  37. * import { fromEvent } from 'rxjs';
  38. * import { throttle } from 'rxjs/operators';
  39. *
  40. * const clicks = fromEvent(document, 'click');
  41. * const result = clicks.pipe(throttle(ev => interval(1000)));
  42. * result.subscribe(x => console.log(x));
  43. * ```
  44. *
  45. * @see {@link audit}
  46. * @see {@link debounce}
  47. * @see {@link delayWhen}
  48. * @see {@link sample}
  49. * @see {@link throttleTime}
  50. *
  51. * @param {function(value: T): SubscribableOrPromise} durationSelector A function
  52. * that receives a value from the source Observable, for computing the silencing
  53. * duration for each source value, returned as an Observable or a Promise.
  54. * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
  55. * to `{ leading: true, trailing: false }`.
  56. * @return {Observable<T>} An Observable that performs the throttle operation to
  57. * limit the rate of emissions from the source.
  58. * @method throttle
  59. * @owner Observable
  60. */
  61. export function throttle<T>(durationSelector: (value: T) => SubscribableOrPromise<any>,
  62. config: ThrottleConfig = defaultThrottleConfig): MonoTypeOperatorFunction<T> {
  63. return (source: Observable<T>) => source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing));
  64. }
  65. class ThrottleOperator<T> implements Operator<T, T> {
  66. constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>,
  67. private leading: boolean,
  68. private trailing: boolean) {
  69. }
  70. call(subscriber: Subscriber<T>, source: any): TeardownLogic {
  71. return source.subscribe(
  72. new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)
  73. );
  74. }
  75. }
  76. /**
  77. * We need this JSDoc comment for affecting ESDoc
  78. * @ignore
  79. * @extends {Ignored}
  80. */
  81. class ThrottleSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {
  82. private _throttled?: Subscription;
  83. private _sendValue?: T;
  84. private _hasValue = false;
  85. constructor(protected destination: Subscriber<T>,
  86. private durationSelector: (value: T) => SubscribableOrPromise<number>,
  87. private _leading: boolean,
  88. private _trailing: boolean) {
  89. super(destination);
  90. }
  91. protected _next(value: T): void {
  92. this._hasValue = true;
  93. this._sendValue = value;
  94. if (!this._throttled) {
  95. if (this._leading) {
  96. this.send();
  97. } else {
  98. this.throttle(value);
  99. }
  100. }
  101. }
  102. private send() {
  103. const { _hasValue, _sendValue } = this;
  104. if (_hasValue) {
  105. this.destination.next(_sendValue);
  106. this.throttle(_sendValue!);
  107. }
  108. this._hasValue = false;
  109. this._sendValue = undefined;
  110. }
  111. private throttle(value: T): void {
  112. const duration = this.tryDurationSelector(value);
  113. if (!!duration) {
  114. this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
  115. }
  116. }
  117. private tryDurationSelector(value: T): SubscribableOrPromise<any> | null {
  118. try {
  119. return this.durationSelector(value);
  120. } catch (err) {
  121. this.destination.error(err);
  122. return null;
  123. }
  124. }
  125. private throttlingDone() {
  126. const { _throttled, _trailing } = this;
  127. if (_throttled) {
  128. _throttled.unsubscribe();
  129. }
  130. this._throttled = undefined;
  131. if (_trailing) {
  132. this.send();
  133. }
  134. }
  135. notifyNext(): void {
  136. this.throttlingDone();
  137. }
  138. notifyComplete(): void {
  139. this.throttlingDone();
  140. }
  141. }