Skip to content

Instantly share code, notes, and snippets.

@sgbasaraner
Created October 21, 2019 18:06
Show Gist options
  • Save sgbasaraner/206e34d43df13e818da6c8b171a08877 to your computer and use it in GitHub Desktop.
Save sgbasaraner/206e34d43df13e818da6c8b171a08877 to your computer and use it in GitHub Desktop.
Coroutines Example
import kotlinx.coroutines.*
import kotlinx.coroutines.experimental.*
import kotlin.system.measureTimeMillis
fun main() {
println("start")
println(bunchOfRequests().toString())
println("stop")
}
fun bunchOfRequests(): Map<String, Long> {
val map = emptyMap<String, Long>().toMutableMap()
runBlocking {
val list: List<Deferred<Map<String, Long>>> = listOf(
async { aRequest(5000) },
async { aRequest(7000) },
async { aRequest(2000) }
)
list.forEach {
it.await().entries.forEach {entry ->
map[entry.key] = entry.value
}
}
}
return map
}
suspend fun aRequest(n: Long): Map<String, Long> {
delay(n)
println(n.toString())
return hashMapOf(n.toString() to n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment