Explicit async

As you saw in the previous chapter, in Kotlin it is very easy to introduce concurrency:

fun getName() = async {
delay(100)
"Ruslan"
}

But that concurrency may be unexpected behavior to the user of the function, as they may expect a simple value:

println("Name: ${getName()}")

It prints:

Name: DeferredCoroutine{Active}@...

Of course, what's missing here is await():

println("Name: ${getName().await()}")

But it would have been a lot more obvious if we'd named our function accordingly:

fun getNameAsync() = async {
delay(100)
"Ruslan"
}

As a rule, you should establish some kind of convention to distinguish async functions from regular ones.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251