tryFinally function

void tryFinally(
  1. dynamic body(),
  2. dynamic whenComplete()
)

Like try/finally, run body and ensure that whenComplete runs afterwards, regardless of whether body succeeded.

This is synchronicity-agnostic relative to body. If body returns a Future, this wil run asynchronously; otherwise it will run synchronously.

Implementation

void tryFinally(Function() body, Function() whenComplete) {
  dynamic result;
  try {
    result = body();
  } catch (_) {
    whenComplete();
    rethrow;
  }

  if (result is! Future) {
    whenComplete();
  } else {
    result.whenComplete(whenComplete);
  }
}