Created
May 1, 2019 10:06
-
-
Save nieldw/924531a2c188e9494eb325b40d6ea436 to your computer and use it in GitHub Desktop.
Observe a rate limit when interacting with an expensive resource
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 kotlin.random.Random | |
fun main() = runBlocking { | |
val start = System.nanoTime() | |
val result = observeRateLimitAsync(1000) { | |
someExpensiveOperationWithRateLimit() | |
}.await() | |
println("Result [$result] retrieved in ${(System.nanoTime() - start) / 1_000_000} ms") | |
} | |
private fun someExpensiveOperationWithRateLimit(): Int { | |
runBlocking { delay(5000) } | |
return Random.nextInt(0, 100) | |
} | |
private suspend fun <T> observeRateLimitAsync(onePerMillis: Long, block: () -> T): Deferred<T> = withContext(Dispatchers.Default) { | |
launch { | |
delay(onePerMillis) | |
println("Rate limit observed: 1 request per $onePerMillis ms") | |
} | |
async { | |
block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment