onExit static method

bool onExit(
  1. FutureOr<void> handler(
    1. ZonedWork<Object?> work
    )
)

Adds an onExit handler to the current ZonedWork instance; if the handler has already been added previously or there is no current ZonedWork instance, then throws a StateError exception.

Parameters:

  • handler: The handler that will be executed after termination.

The handler will be executed once in one of the following cases (whichever comes first):

  • The computation will complete with a result or with an error
  • The computation will terminate due to the call to the terminate method
  • The computation will terminate in an unpredictable way

The handler will be executed in the root zone and it should not throw exceptions.

Example:

if (ZonedWork.current != null) {
  ZonedWork.onExit((work) {
    // Free resources, close handles, cancel operations
  });
}

Implementation

static bool onExit(FutureOr<void> Function(ZonedWork<Object?> work) handler) {
  final current = ZonedWork.current;
  if (current == null) {
    throw StateError(
        "Failed to add `onExit()` handler, no current instance of 'ZonedWork'");
  }

  if (current._onExit != null) {
    throw StateError("'ZonedWork.onExit()' can only be called once");
  }

  current._onExit = handler;
  return true;
}