Skip to content

Instantly share code, notes, and snippets.

@nieldw
Created May 1, 2019 10:06
Show Gist options
  • Save nieldw/924531a2c188e9494eb325b40d6ea436 to your computer and use it in GitHub Desktop.
Save nieldw/924531a2c188e9494eb325b40d6ea436 to your computer and use it in GitHub Desktop.
Observe a rate limit when interacting with an expensive resource
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