There are two ways to define asynchronous functions in Kotlin:
suspend in the function declaration 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.
suspend fun CoroutineScope.f(): Int {
val resource1 = loadResource1()
val resource2 = loadResource2()
return resource1.size + resource2.size
}
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
}