Skip to content

Instantly share code, notes, and snippets.

@christianb
Last active January 8, 2021 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianb/aabc665e59cd59990a515ef6a6d45190 to your computer and use it in GitHub Desktop.
Save christianb/aabc665e59cd59990a515ef6a6d45190 to your computer and use it in GitHub Desktop.
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