throttleTime.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Subscriber } from '../Subscriber';
  2. import { async } from '../scheduler/async';
  3. import { defaultThrottleConfig } from './throttle';
  4. export function throttleTime(duration, scheduler = async, config = defaultThrottleConfig) {
  5. return (source) => source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
  6. }
  7. class ThrottleTimeOperator {
  8. constructor(duration, scheduler, leading, trailing) {
  9. this.duration = duration;
  10. this.scheduler = scheduler;
  11. this.leading = leading;
  12. this.trailing = trailing;
  13. }
  14. call(subscriber, source) {
  15. return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
  16. }
  17. }
  18. class ThrottleTimeSubscriber extends Subscriber {
  19. constructor(destination, duration, scheduler, leading, trailing) {
  20. super(destination);
  21. this.duration = duration;
  22. this.scheduler = scheduler;
  23. this.leading = leading;
  24. this.trailing = trailing;
  25. this._hasTrailingValue = false;
  26. this._trailingValue = null;
  27. }
  28. _next(value) {
  29. if (this.throttled) {
  30. if (this.trailing) {
  31. this._trailingValue = value;
  32. this._hasTrailingValue = true;
  33. }
  34. }
  35. else {
  36. this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
  37. if (this.leading) {
  38. this.destination.next(value);
  39. }
  40. }
  41. }
  42. _complete() {
  43. if (this._hasTrailingValue) {
  44. this.destination.next(this._trailingValue);
  45. this.destination.complete();
  46. }
  47. else {
  48. this.destination.complete();
  49. }
  50. }
  51. clearThrottle() {
  52. const throttled = this.throttled;
  53. if (throttled) {
  54. if (this.trailing && this._hasTrailingValue) {
  55. this.destination.next(this._trailingValue);
  56. this._trailingValue = null;
  57. this._hasTrailingValue = false;
  58. }
  59. throttled.unsubscribe();
  60. this.remove(throttled);
  61. this.throttled = null;
  62. }
  63. }
  64. }
  65. function dispatchNext(arg) {
  66. const { subscriber } = arg;
  67. subscriber.clearThrottle();
  68. }
  69. //# sourceMappingURL=throttleTime.js.map