Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

AsyncScheduler.ts 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { Scheduler } from '../Scheduler';
  2. import { Action } from './Action';
  3. import { AsyncAction } from './AsyncAction';
  4. import { SchedulerAction } from '../types';
  5. import { Subscription } from '../Subscription';
  6. export class AsyncScheduler extends Scheduler {
  7. public static delegate?: Scheduler;
  8. public actions: Array<AsyncAction<any>> = [];
  9. /**
  10. * A flag to indicate whether the Scheduler is currently executing a batch of
  11. * queued actions.
  12. * @type {boolean}
  13. * @deprecated internal use only
  14. */
  15. public active: boolean = false;
  16. /**
  17. * An internal ID used to track the latest asynchronous task such as those
  18. * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
  19. * others.
  20. * @type {any}
  21. * @deprecated internal use only
  22. */
  23. public scheduled: any = undefined;
  24. constructor(SchedulerAction: typeof Action,
  25. now: () => number = Scheduler.now) {
  26. super(SchedulerAction, () => {
  27. if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
  28. return AsyncScheduler.delegate.now();
  29. } else {
  30. return now();
  31. }
  32. });
  33. }
  34. public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {
  35. if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
  36. return AsyncScheduler.delegate.schedule(work, delay, state);
  37. } else {
  38. return super.schedule(work, delay, state);
  39. }
  40. }
  41. public flush(action: AsyncAction<any>): void {
  42. const {actions} = this;
  43. if (this.active) {
  44. actions.push(action);
  45. return;
  46. }
  47. let error: any;
  48. this.active = true;
  49. do {
  50. if (error = action.execute(action.state, action.delay)) {
  51. break;
  52. }
  53. } while (action = actions.shift()); // exhaust the scheduler queue
  54. this.active = false;
  55. if (error) {
  56. while (action = actions.shift()) {
  57. action.unsubscribe();
  58. }
  59. throw error;
  60. }
  61. }
  62. }