BackOff<T> constructor

BackOff<T>(
  1. FutureOr<T> func(), {
  2. Duration initialDelay = const Duration(milliseconds: 200),
  3. double percentageRandomization = 0.25,
  4. Duration maxDelay = const Duration(seconds: 30),
  5. int maxAttempts = 8,
  6. FutureOr<bool> retryIf(
    1. Object error,
    2. StackTrace stackTrace,
    3. int attempt
    )?,
})

BackOff is used for holding options for retrying a function.

With the default configuration functions will be retried up-to 7 times (8 attempts in total), sleeping 1st, 2nd, 3rd, ..., 7th attempt:

  1. 400 ms ± 25%
  2. 800 ms ± 25%
  3. 1600 ms ± 25%
  4. 3200 ms ± 25%
  5. 6400 ms ± 25%
  6. 12800 ms ± 25%
  7. 25600 ms ± 25%

Usage Example:


final response = await BackOff(
  () => http.get('https://google.com').timeout(
         const Duration(seconds: 10),
      ),
  retryIf: (error, stackTrace, attempt) => error is SocketException || error is TimeoutException,
  initialDelay: const Duration(milliseconds: 200),
  maxAttempts: 8,
  percentageRandomization: 0.25,
  maxDelay: const Duration(seconds: 30),
).call();

print(response.body);

Implementation

BackOff(
  this.func, {
  this.initialDelay = const Duration(milliseconds: 200),
  this.percentageRandomization = 0.25,
  this.maxDelay = const Duration(seconds: 30),
  this.maxAttempts = 8,
  this.retryIf,
})  : assert(!initialDelay.isNegative, '❌ [Bad] [Duration] initialDelay must be positive!'),
      assert(!maxDelay.isNegative, '❌ [Bad] [Duration] maxDelay must be positive!'),
      assert(maxAttempts > 0, '❌ [Bad] [int] maxAttempts must be greater than 0!');