Implementing a Retry Mechanism with Coroutines in Kotlin for Network Failures
https://medium.com/@mohamed.ma872/implementing-a-retry-mechanism-with-coroutines-in-kotlin-for-network-failures-6dff04d26c14
import kotlinx.coroutines.delay
suspend fun <T> retryCoroutine(
maxAttempts: Int = 3,
initialDelay: Long = 1000, // Initial delay in milliseconds
maxDelay: Long = 3000, // Max delay in milliseconds
factor: Double = 2.0, // Factor to increase the delay each retry
block: suspend () -> T // The suspend function that makes the network request
): T {
var currentDelay = initialDelay
repeat(maxAttempts - 1) { attempt ->
try {
return block() // Try to execute the block
} catch (e: Exception) {
println("Attempt ${attempt + 1} failed: ${e.message}")
delay(currentDelay)
currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay)
}
}
return block() // Last attempt, throw exception if it fails
}