observeSync<T> function

T observeSync<T>(
  1. T operation(), {
  2. void onSuccess(
    1. Duration elapsed,
    2. T result
    )?,
  3. void onError(
    1. Duration elapsed,
    2. Object error,
    3. StackTrace stackTrace
    )?,
})

Synchronous counterpart of observeAsync: times operation, reports the outcome through the optional hooks, and returns the result (or rethrows after onError). Audited: 2026-06-12 11:26 EDT

Implementation

T observeSync<T>(
  T Function() operation, {
  void Function(Duration elapsed, T result)? onSuccess,
  void Function(Duration elapsed, Object error, StackTrace stackTrace)? onError,
}) {
  final Stopwatch stopwatch = Stopwatch()..start();
  try {
    final T result = operation();
    stopwatch.stop();
    onSuccess?.call(stopwatch.elapsed, result);
    return result;
  } on Object catch (error, stackTrace) {
    // Catch-all is intentional (see observeAsync): time and report every
    // failure, then rethrow so the wrapper never alters control flow.
    stopwatch.stop();
    onError?.call(stopwatch.elapsed, error, stackTrace);
    rethrow;
  }
}