runGuardedAsync<T> method
Future<T?>
runGuardedAsync<T>(
- FutureOr<
T> action(), { - bool cancelOnClose = true,
- void onError(
- Object error,
- StackTrace stackTrace
Executes action and suppresses its result if this controller closes first.
This is a cooperative lifecycle guard: it does not cancel the underlying
operation, but it prevents stale post-await code from using a result after
disposal when cancelOnClose is true.
If cancelOnClose is true and the controller is already closed, this
method returns null without invoking action.
If onError is provided, it is called before re-throwing any error from action.
Returns the computed value when still valid for this lifecycle, otherwise null.
Throws any error thrown by action.
Implementation
Future<T?> runGuardedAsync<T>(
FutureOr<T> Function() action, {
bool cancelOnClose = true,
void Function(Object error, StackTrace stackTrace)? onError,
}) async {
if (cancelOnClose && isClosed) return null;
try {
final result = await action();
if (cancelOnClose && isClosed) return null;
return result;
} catch (e, s) {
onError?.call(e, s);
rethrow;
}
}