Hi, I have a doubt about calling suspend functions from an async(UI) block:
Fredy Mederos
1

In your example `largeOperation` will be called on UI thread. You should use `async/await` to specify background context, so your code executes in background. (suspended function doesn’t mean it’s executed in background, it means it will be executed on coroutine context, in your case UI)

Try to play with this code, add log which shows if you are currently on main/background thread.

Here is version which runs on background thread:

fun largeOperation() = async(CommonPool) {
delay(2_000)
return "result"
}
fun loadData() = async(UI) {
startLoading() //ui thread
var result = largeOperation().await() //suspended
toast(result) //ui thread
}
Like what you read? Give Dmytro Danylyk a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.