There are two ways to define asynchronous functions in Kotlin:
- using the modifier
suspend
in the function declaration
- creating an extension function on
CoroutineScope
(or passing it as a parameter)
The suspend
modifier is generally used for functions that might take some time to complete. The caller coroutine might be potentially
suspended.
Functions that return results immediately but start a coroutine in the background should be written as extension functions on
CoroutineScope
. At the same time, these functions should not be declared suspend
, as suspending functions should not leave
running background tasks behind.
Noncompliant code example
suspend fun CoroutineScope.f(): Int {
val resource1 = loadResource1()
val resource2 = loadResource2()
return resource1.size + resource2.size
}
Compliant solution
Using suspend
:
suspend fun f(): Int {
val resource1 = loadResource1()
val resource2 = loadResource2()
return resource1.size + resource2.size
}
Using extension on CoroutineScope
:
fun CoroutineScope.f(): Deferred<Int> = async {
val resource1 = loadResource1()
val resource2 = loadResource2()
resource1.size + resource2.size
}