runAndCloseAsync<R> method
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
Future<R> runAndCloseAsync<R>(FutureOr<R> Function(Closeable p0) fn) async {
Object? exception;
if (_closed) {
exception = StateError('Resource is already closed');
}
R? result;
try {
result = await fn(this);
} on Object catch (e) {
exception ??= e;
}
try {
await close();
} on Object catch (e) {
exception ??= e;
}
final Iterable<Object?> futures = await Future.wait(
closeables.map(
(c) => c
.runAndCloseAsync((_) => null as Object?)
.catchError((Object e) => e),
),
);
exception ??= futures.firstWhere(
(e) => e != null,
orElse: () => null,
);
_closed = true;
if (exception != null) {
_wrapAndThrow(exception);
} else {
return result as R;
}
}