RealTimeNgZoneStabilizer constructor

RealTimeNgZoneStabilizer(
  1. TimerHookZone timerZone,
  2. NgZone ngZone
)

Creates a new stabilizer which manages a custom zone around an NgZone.

Implementation

factory RealTimeNgZoneStabilizer(TimerHookZone timerZone, NgZone ngZone) {
  // All non-periodic timers that have been started, but not completed.
  final pendingTimers = PriorityQueue<_ObservedTimer>();
  timerZone.createTimer = (
    self,
    parent,
    zone,
    duration,
    callback,
  ) {
    // If the timer is meant to run outside of Angular zone, we do not try to
    // stabilize it, and delegate it to the parent zone.
    if (!inAngularZone(ngZone, zone)) {
      return parent.createTimer(zone, duration, callback);
    }

    late final _ObservedTimer instance;
    void wrappedCallback() {
      try {
        callback();
      } finally {
        pendingTimers.remove(instance);
      }
    }

    final delegate = parent.createTimer(
      zone,
      duration,
      wrappedCallback,
    );
    instance = _ObservedTimer(
      delegate,
      duration,
      () => pendingTimers.remove(instance),
    );
    pendingTimers.add(instance);
    return instance;
  };
  return RealTimeNgZoneStabilizer._(
    ngZone,
    pendingTimers,
  );
}