retry With Backoff
Runs block until it succeeds, at most times times, with a longer pause after each failure.
Returns the first successful result. When every attempt fails, it throws the failure of the last attempt, unchanged.
Example
val user = retryWithBackoff(
times = 5,
initialDelay = 100.milliseconds,
maxDelay = 1.seconds,
) {
withTimeout(2.seconds) { api.fetchUser(id) }
}
// Pauses between the 5 attempts: 100 ms, 200 ms, 400 ms, 800 ms.Cancellation
When the caller is cancelled, the retries stop at once and the cancellation is thrown. It is never retried, and retryIf never sees it.
A CancellationException from inside block, while the caller is still active, is an ordinary failure. So a timeout of a
withTimeoutinside block is retried, as in the example.
Parameters
the maximum number of attempts, first attempt included. At least 1. times = 3 means one attempt and up to two retries.
the pause after the first failure. Zero or more.
each pause is the previous pause times factor. 2.0 doubles it. 1.0 keeps a fixed pause. Must be a positive finite number.
the longest pause. Zero or more. The default means no limit.
returns true for a failure that should be retried. A failure that it rejects is thrown at once. The default retries every failure.
the work. Its parameter is the attempt number, starting at 1.
Throws
if times is less than 1, initialDelay or maxDelay is negative, or factor is not a positive finite number.