Last active
January 30, 2026 15:54
-
-
Save padymont/9fe949f459d145d97ffe60d7bae0e045 to your computer and use it in GitHub Desktop.
Polling 30012026
This file contains hidden or 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
| // 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