https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sourabh Rawat

06/22/2021, 7:00 PM
when to use "suspend function" vs "function returning Deferred"?
d

Dominaezzz

06/22/2021, 7:05 PM
Never return Deferred. (There are use cases for returning Deferred, but if you have to ask, you don't have that use case)
👍🏼 1
☝️ 8
☝🏼 2
👍 3
c

Casey Brooks

06/22/2021, 7:10 PM
Deferred
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.
🙏 2
1
s

Sourabh Rawat

06/22/2021, 7:40 PM
generally, don’t use coroutine builders inside a function
what is the reason behind this?
c

Casey Brooks

06/22/2021, 9:08 PM
Because it prevents you from combining those functions, and will probably lead you to doing Very Bad Things™️ with those functions. This is what a code snippet might look like trying to combine functions that use builders internally:
Copy code
fun 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:
Copy code
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")
}
But like Dominic said above, there are use-cases for using coroutine builders inside the body of a function or returning a Deferred, but if you have to ask, then you don’t have that use-case
g

gildor

06/23/2021, 8:21 AM
It’s completely fine to use coroutine builders inside of a suspend function, if this function has own coroutine scope like”
Copy code
suspend 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
2
2 Views