runAndClose<R> method

R runAndClose<R>(
  1. R fn(
    1. C p0
    )
)

Runs passed function and closes this resource after it Closes the resource even if the function throws. The first exception thrown is propagated, if both the function and the close throw, the exception from the function is propagated

Implementation

R runAndClose<R>(R Function(C p0) fn) {
  Object? exception;
  if (_closed) {
    exception = StateError('Resource is already closed');
  }
  R? result;
  try {
    result = fn(this);
  } on Object catch (e) {
    exception ??= e;
  }

  try {
    _closeSync();
  } on Object catch (e) {
    exception ??= e;
  }

  for (final closeable in closeables) {
    try {
      closeable.runAndClose<void>((_) {});
    } on Object catch (e) {
      exception ??= e;
    }
  }

  _closed = true;
  if (exception != null) {
    _wrapAndThrow(exception);
  }

  return result as R;
}