run<T> static method

Future<T> run<T>(
  1. FutureOr<T> callback(), [
  2. CancelToken? cancelToken
])

Returns result of the provided callback using the exponential backoff algorithm on any errors.

Implementation

static Future<T> run<T>(
  FutureOr<T> Function() callback, [
  CancelToken? cancelToken,
]) async {
  final CancelableOperation operation = CancelableOperation.fromFuture(
    Future(() async {
      Duration backoff = Duration.zero;

      while (true) {
        await Future.delayed(backoff);
        if (cancelToken?.isCancelled == true) {
          throw OperationCanceledException();
        }

        try {
          return await callback();
        } catch (e, _) {
          if (backoff.inMilliseconds == 0) {
            backoff = _minBackoff;
          } else if (backoff < _maxBackoff) {
            backoff *= 2;
          }

          Log.debug(e.toString(), 'Backoff');
        }
      }
    }),
  );

  cancelToken?.whenCancel.then((_) => operation.cancel());

  final result = await operation.valueOrCancellation();
  if (operation.isCanceled) {
    throw OperationCanceledException();
  }

  return result;
}