Created
February 9, 2025 07:45
-
-
Save raghunandankavi2010/2f1b699a5a7db52866178c890fc94f6c to your computer and use it in GitHub Desktop.
Retry with exponential back off coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import java.io.IOException | |
suspend fun <T> retryIO( | |
times: Int = Int.MAX_VALUE, | |
initialDelay: Long = 100, // 0.1 second | |
maxDelay: Long = 1000, // 1 second | |
factor: Double = 2.0, | |
block: suspend () -> T | |
): T { | |
var currentDelay = initialDelay | |
repeat(times - 1) { | |
try { | |
return block() | |
} catch (e: IOException) { | |
println("Retrying due to: ${e.message}") | |
} | |
delay(currentDelay) | |
currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) | |
} | |
return block() // last attempt | |
} | |
fun main() = runBlocking<Unit> { | |
try { | |
val result = retryIO(times = 5) { | |
getResult() | |
} | |
println("Final result: $result") | |
} catch(ex: Exception) { | |
println("All tries failed due to: ${ex.message}") | |
} | |
} | |
suspend fun getResult(): String { | |
//throw IOException("Simulated IO exception") | |
return "Success" | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment