Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

throttle.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { OuterSubscriber } from '../OuterSubscriber';
  2. import { subscribeToResult } from '../util/subscribeToResult';
  3. export const defaultThrottleConfig = {
  4. leading: true,
  5. trailing: false
  6. };
  7. export function throttle(durationSelector, config = defaultThrottleConfig) {
  8. return (source) => source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
  9. }
  10. class ThrottleOperator {
  11. constructor(durationSelector, leading, trailing) {
  12. this.durationSelector = durationSelector;
  13. this.leading = leading;
  14. this.trailing = trailing;
  15. }
  16. call(subscriber, source) {
  17. return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
  18. }
  19. }
  20. class ThrottleSubscriber extends OuterSubscriber {
  21. constructor(destination, durationSelector, _leading, _trailing) {
  22. super(destination);
  23. this.destination = destination;
  24. this.durationSelector = durationSelector;
  25. this._leading = _leading;
  26. this._trailing = _trailing;
  27. this._hasValue = false;
  28. }
  29. _next(value) {
  30. this._hasValue = true;
  31. this._sendValue = value;
  32. if (!this._throttled) {
  33. if (this._leading) {
  34. this.send();
  35. }
  36. else {
  37. this.throttle(value);
  38. }
  39. }
  40. }
  41. send() {
  42. const { _hasValue, _sendValue } = this;
  43. if (_hasValue) {
  44. this.destination.next(_sendValue);
  45. this.throttle(_sendValue);
  46. }
  47. this._hasValue = false;
  48. this._sendValue = null;
  49. }
  50. throttle(value) {
  51. const duration = this.tryDurationSelector(value);
  52. if (!!duration) {
  53. this.add(this._throttled = subscribeToResult(this, duration));
  54. }
  55. }
  56. tryDurationSelector(value) {
  57. try {
  58. return this.durationSelector(value);
  59. }
  60. catch (err) {
  61. this.destination.error(err);
  62. return null;
  63. }
  64. }
  65. throttlingDone() {
  66. const { _throttled, _trailing } = this;
  67. if (_throttled) {
  68. _throttled.unsubscribe();
  69. }
  70. this._throttled = null;
  71. if (_trailing) {
  72. this.send();
  73. }
  74. }
  75. notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  76. this.throttlingDone();
  77. }
  78. notifyComplete() {
  79. this.throttlingDone();
  80. }
  81. }
  82. //# sourceMappingURL=throttle.js.map