cf2ce8ff230692c1054e016083014c4ac20325f3f8f2b1d4031370ba38669e262310f46bc36ce52d8736360b0f3fdd5902d2517cf8f6916a88c82a9d1f0ebf 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import { Action } from './Action';
  2. import { SchedulerAction } from '../types';
  3. import { Subscription } from '../Subscription';
  4. import { AsyncScheduler } from './AsyncScheduler';
  5. import { intervalProvider } from './intervalProvider';
  6. import { arrRemove } from '../util/arrRemove';
  7. import { TimerHandle } from './timerHandle';
  8. export class AsyncAction<T> extends Action<T> {
  9. public id: TimerHandle | undefined;
  10. public state?: T;
  11. // @ts-ignore: Property has no initializer and is not definitely assigned
  12. public delay: number;
  13. protected pending: boolean = false;
  14. constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {
  15. super(scheduler, work);
  16. }
  17. public schedule(state?: T, delay: number = 0): Subscription {
  18. if (this.closed) {
  19. return this;
  20. }
  21. // Always replace the current state with the new state.
  22. this.state = state;
  23. const id = this.id;
  24. const scheduler = this.scheduler;
  25. //
  26. // Important implementation note:
  27. //
  28. // Actions only execute once by default, unless rescheduled from within the
  29. // scheduled callback. This allows us to implement single and repeat
  30. // actions via the same code path, without adding API surface area, as well
  31. // as mimic traditional recursion but across asynchronous boundaries.
  32. //
  33. // However, JS runtimes and timers distinguish between intervals achieved by
  34. // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
  35. // serial `setTimeout` calls can be individually delayed, which delays
  36. // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
  37. // guarantee the interval callback will be invoked more precisely to the
  38. // interval period, regardless of load.
  39. //
  40. // Therefore, we use `setInterval` to schedule single and repeat actions.
  41. // If the action reschedules itself with the same delay, the interval is not
  42. // canceled. If the action doesn't reschedule, or reschedules with a
  43. // different delay, the interval will be canceled after scheduled callback
  44. // execution.
  45. //
  46. if (id != null) {
  47. this.id = this.recycleAsyncId(scheduler, id, delay);
  48. }
  49. // Set the pending flag indicating that this action has been scheduled, or
  50. // has recursively rescheduled itself.
  51. this.pending = true;
  52. this.delay = delay;
  53. // If this action has already an async Id, don't request a new one.
  54. this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);
  55. return this;
  56. }
  57. protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {
  58. return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
  59. }
  60. protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {
  61. // If this action is rescheduled with the same delay time, don't clear the interval id.
  62. if (delay != null && this.delay === delay && this.pending === false) {
  63. return id;
  64. }
  65. // Otherwise, if the action's delay time is different from the current delay,
  66. // or the action has been rescheduled before it's executed, clear the interval id
  67. if (id != null) {
  68. intervalProvider.clearInterval(id);
  69. }
  70. return undefined;
  71. }
  72. /**
  73. * Immediately executes this action and the `work` it contains.
  74. */
  75. public execute(state: T, delay: number): any {
  76. if (this.closed) {
  77. return new Error('executing a cancelled action');
  78. }
  79. this.pending = false;
  80. const error = this._execute(state, delay);
  81. if (error) {
  82. return error;
  83. } else if (this.pending === false && this.id != null) {
  84. // Dequeue if the action didn't reschedule itself. Don't call
  85. // unsubscribe(), because the action could reschedule later.
  86. // For example:
  87. // ```
  88. // scheduler.schedule(function doWork(counter) {
  89. // /* ... I'm a busy worker bee ... */
  90. // var originalAction = this;
  91. // /* wait 100ms before rescheduling the action */
  92. // setTimeout(function () {
  93. // originalAction.schedule(counter + 1);
  94. // }, 100);
  95. // }, 1000);
  96. // ```
  97. this.id = this.recycleAsyncId(this.scheduler, this.id, null);
  98. }
  99. }
  100. protected _execute(state: T, _delay: number): any {
  101. let errored: boolean = false;
  102. let errorValue: any;
  103. try {
  104. this.work(state);
  105. } catch (e) {
  106. errored = true;
  107. // HACK: Since code elsewhere is relying on the "truthiness" of the
  108. // return here, we can't have it return "" or 0 or false.
  109. // TODO: Clean this up when we refactor schedulers mid-version-8 or so.
  110. errorValue = e ? e : new Error('Scheduled action threw falsy error');
  111. }
  112. if (errored) {
  113. this.unsubscribe();
  114. return errorValue;
  115. }
  116. }
  117. unsubscribe() {
  118. if (!this.closed) {
  119. const { id, scheduler } = this;
  120. const { actions } = scheduler;
  121. this.work = this.state = this.scheduler = null!;
  122. this.pending = false;
  123. arrRemove(actions, this);
  124. if (id != null) {
  125. this.id = this.recycleAsyncId(scheduler, id, null);
  126. }
  127. this.delay = null!;
  128. super.unsubscribe();
  129. }
  130. }
  131. }