Sourabh Rawat
06/22/2021, 7:00 PMDominaezzz
06/22/2021, 7:05 PMCasey Brooks
06/22/2021, 7:10 PMDeferred
comes from the async { }
builder, which is designed for spawning multiple parallel tasks and giving you a way to wait for them to finish and aggregate the results, A single function that would return a Deferred is essentially saying ārun this function asynchronously and return a result`, which is exactly the same sentiment as a normal suspend
function, but with an extra step.
So donāt return Deferred
, and generally, donāt use coroutine builders inside a function. Just mark the function suspend and wrap it in the appropriate coroutine builder at the call-site.Sourabh Rawat
06/22/2021, 7:40 PMgenerally, donāt use coroutine buildersĀ insideĀ a functionwhat is the reason behind this?
Casey Brooks
06/22/2021, 9:08 PMfun CoroutineScope.asyncMethod1(): Deferred<Int> = async {
delay(1.seconds)
1
}
fun CoroutineScope.asyncMethod2(someValue: Int) = launch {
delay(1.seconds)
}
fun main() = runBlocking {
val value1 = asyncMethod1().await()
asyncMethod2(value1).join()
println("finished")
}
and hereās what it should look like:
suspend fun asyncMethod1(): Int {
delay(1.seconds)
return 1
}
suspend fun asyncMethod2(someValue: Int) {
delay(1.seconds)
}
fun main() = runBlocking {
val value1 = asyncMethod1()
asyncMethod2(value1)
println("finished")
}
Casey Brooks
06/22/2021, 9:08 PMgildor
06/23/2021, 8:21 AMsuspend fun doSomething() = coroutineScope {
// here you can call any coroutine builders to run multiple coroutines in parallel, scope will return only when all those coroutines are finished
}
But using top level coroutine builder (and pass scope as argument of a function), is usually a bad solution