Last active
January 8, 2021 10:09
-
-
Save christianb/aabc665e59cd59990a515ef6a6d45190 to your computer and use it in GitHub Desktop.
Stack Overflow Answer https://stackoverflow.com/questions/65197276/
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.flow.* | |
import kotlin.random.Random | |
fun main() = runBlocking { | |
val providers: List<Provider> = listOf(Provider("p1"), Provider("p2"), Provider("p3")) | |
println(executeAllProviderAsync(providers)) | |
} | |
suspend fun executeAllProviderAsync(providers: List<Provider>): List<Int> = withContext(Dispatchers.Default){ | |
return@withContext providers.map { | |
async { it.execute() } | |
}.awaitAll().flatten() | |
} | |
class Provider(private val name: String) { | |
suspend fun execute(): List<Int> = withContext(Dispatchers.Default) { | |
val delay = Random.nextLong(500, 2500) | |
println("execute Provider '$name' with delay: $delay") | |
delay(delay) | |
return@withContext listOf(Random.nextInt(), Random.nextInt()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment