Making asynchronicity explicit
In Kotlin, managing asynchronous operations is streamlined with coroutines. However, the asynchronous nature of a function is not always apparent from its name or signature, which can lead to misunderstandings about its behavior.
Consider a simple asynchronous function defined within a CoroutineScope
:
fun CoroutineScope.getResult() = async {
delay(100)
"OK"
}
Since this function implicitly returns a Deferred
object, not the direct result, the following code might not behave as expected:
println("Result: ${getResult()}")
This prints a reference to the Deferred
object instead of OK
:
> Result: DeferredCoroutine{Active}@...
If you’ve been following along with the book, you will already know that to obtain the actual result, the await()
function must be used:
println("Result: ${getResultAsync().await()}")
This code correctly waits for Deferred
to complete and then prints...