575fcd0b17c58043d00e79cc8b83be04d49b52152de1b6d9d1227a5e8b25c2249ab63835aca39c652fc9fc5cd146460596bdf8f683d15a0210f6934a8526d8 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { AsyncAction } from './AsyncAction';
  2. import { AsapScheduler } from './AsapScheduler';
  3. import { SchedulerAction } from '../types';
  4. import { immediateProvider } from './immediateProvider';
  5. import { TimerHandle } from './timerHandle';
  6. export class AsapAction<T> extends AsyncAction<T> {
  7. constructor(protected scheduler: AsapScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {
  8. super(scheduler, work);
  9. }
  10. protected requestAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {
  11. // If delay is greater than 0, request as an async action.
  12. if (delay !== null && delay > 0) {
  13. return super.requestAsyncId(scheduler, id, delay);
  14. }
  15. // Push the action to the end of the scheduler queue.
  16. scheduler.actions.push(this);
  17. // If a microtask has already been scheduled, don't schedule another
  18. // one. If a microtask hasn't been scheduled yet, schedule one now. Return
  19. // the current scheduled microtask id.
  20. return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));
  21. }
  22. protected recycleAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {
  23. // If delay exists and is greater than 0, or if the delay is null (the
  24. // action wasn't rescheduled) but was originally scheduled as an async
  25. // action, then recycle as an async action.
  26. if (delay != null ? delay > 0 : this.delay > 0) {
  27. return super.recycleAsyncId(scheduler, id, delay);
  28. }
  29. // If the scheduler queue has no remaining actions with the same async id,
  30. // cancel the requested microtask and set the scheduled flag to undefined
  31. // so the next AsapAction will request its own.
  32. const { actions } = scheduler;
  33. if (id != null && actions[actions.length - 1]?.id !== id) {
  34. immediateProvider.clearImmediate(id);
  35. if (scheduler._scheduled === id) {
  36. scheduler._scheduled = undefined;
  37. }
  38. }
  39. // Return undefined so the action knows to request a new async id if it's rescheduled.
  40. return undefined;
  41. }
  42. }