Skip to content

Instantly share code, notes, and snippets.

@padymont
Last active January 30, 2026 15:54
Show Gist options
  • Select an option

  • Save padymont/9fe949f459d145d97ffe60d7bae0e045 to your computer and use it in GitHub Desktop.

Select an option

Save padymont/9fe949f459d145d97ffe60d7bae0e045 to your computer and use it in GitHub Desktop.
Polling 30012026
// Task:
// Implement polling with a timeout
suspend fun makeNetworkRequest(): Result<String> {
delay(100)
return if (Random.nextBoolean()) {
Result.success("hello")
} else {
Result.failure(RuntimeException("Bad luck"))
}
}
// Rewrite the method:
suspend fun pollNetworkCall(): Result<String> {
return makeNetworkRequest()
}
// Solution:
suspend fun pollNetworkCall(
timeoutMillis: Long,
initialDelay: Long = 500L,
maxDelay: Long = 4000L
): Result<String> {
var currentDelay = initialDelay
var result: Result<String>? = null
withTimeout(timeoutMillis) {
while (true) {
val localResult = makeNetworkRequest()
if (localResult.isSuccess) {
result = localResult
return@withTimeout
} else {
delay(currentDelay)
currentDelay = (currentDelay * 2).coerceAtMost(maxDelay)
}
}
}
return result ?: Result.failure(
TimeoutException("Timed out after $timeoutMillis ms")
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment