throttle.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { operate } from '../util/lift';
  2. import { createOperatorSubscriber } from './OperatorSubscriber';
  3. import { innerFrom } from '../observable/innerFrom';
  4. export function throttle(durationSelector, config) {
  5. return operate((source, subscriber) => {
  6. const { leading = true, trailing = false } = config !== null && config !== void 0 ? config : {};
  7. let hasValue = false;
  8. let sendValue = null;
  9. let throttled = null;
  10. let isComplete = false;
  11. const endThrottling = () => {
  12. throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
  13. throttled = null;
  14. if (trailing) {
  15. send();
  16. isComplete && subscriber.complete();
  17. }
  18. };
  19. const cleanupThrottling = () => {
  20. throttled = null;
  21. isComplete && subscriber.complete();
  22. };
  23. const startThrottle = (value) => (throttled = innerFrom(durationSelector(value)).subscribe(createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));
  24. const send = () => {
  25. if (hasValue) {
  26. hasValue = false;
  27. const value = sendValue;
  28. sendValue = null;
  29. subscriber.next(value);
  30. !isComplete && startThrottle(value);
  31. }
  32. };
  33. source.subscribe(createOperatorSubscriber(subscriber, (value) => {
  34. hasValue = true;
  35. sendValue = value;
  36. !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
  37. }, () => {
  38. isComplete = true;
  39. !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
  40. }));
  41. });
  42. }
  43. //# sourceMappingURL=throttle.js.map