Created
October 21, 2019 18:06
-
-
Save sgbasaraner/206e34d43df13e818da6c8b171a08877 to your computer and use it in GitHub Desktop.
Coroutines Example
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
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