Nino
08/11/2022, 1:46 PMinitializeStuffAndGetFoo()
function between my coroutines without this dangerous first() as String
?
https://pl.kotl.in/7fVqO3EXP
import kotlinx.coroutines.*
fun main() = runBlocking {
println(initializeStuffAndGetFoo())
}
suspend fun initializeStuffAndGetFoo() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
listOf(
async { getFooValue() },
async { initA() },
async { initB() },
).awaitAll().first() as String
}
suspend fun getFooValue(): String {
delay(2_000)
return "Foo"
}
suspend fun initA() = delay(1_000)
suspend fun initB() = delay(3_000)
async
starts eagerly by default so we can use something like that, can't we ?
import kotlinx.coroutines.*
fun main() = runBlocking {
println(initializeStuffAndGetFoo())
}
suspend fun initializeStuffAndGetFoo() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
val fooAsync = async { getFooValue() }
listOf(
async { initA() },
async { initB() },
).awaitAll()
fooAsync.await()
}
suspend fun getFooValue(): String {
delay(2_000)
return "Foo"
}
suspend fun initA() = delay(1_000)
suspend fun initB() = delay(3_000)
Joffrey
08/11/2022, 2:03 PMasync
, you could use lauch
for the other 2 and not even await them (withContext
would do it)Nino
08/11/2022, 2:05 PMinitA()
and initB()
become sequential this way ?import kotlinx.coroutines.*
fun main() = runBlocking {
println(initializeStuffAndGetFoo())
}
suspend fun initializeStuffAndGetFoo() = coroutineScope {
launch { initA() }
launch { initB() }
getFooValue()
}
suspend fun getFooValue(): String {
println("Waiting for foo value...")
delay(2_000)
println("Waiting for foo value done!")
return "Foo"
}
suspend fun initA() {
println("Waiting for A...")
delay(1_000)
println("Waiting for A done!")
}
suspend fun initB() {
println("Waiting for B...")
delay(3_000)
println("Waiting for B done!")
}
Joffrey
08/11/2022, 2:57 PMNino
08/11/2022, 2:58 PM