Reputation: 806
I have been wrapping my head around coroutines and I was wondering about the following code. I have the following operation on my onCreate().
asyncJob = GlobalScope.launch(Dispatchers.Main) {
val name = async(Dispatchers.Default) { queryDevices() }.await()
mDeviceName.text = deviceName
}
Printing this out the order of execution seems to be before "name" is on UI thread and after name is set, it is on the UI thread as well. The queryDevicesMethod() is in a background thread as expected.
But I wanted to know what await() is actually doing when calling it on the UI thread? Is it blocking theUI thread until await returns?
Upvotes: 2
Views: 2315
Reputation: 6248
Coroutines will not block the thread on suspending. The Kotlin compiler generates a state machine that detaches and attaches the coroutines from the thread, see https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md.
In your case GlobalScope.launch(Dispatchers.Main)
starts a new coroutine confined to the UI thread. Then async()
starts a new coroutine confined to another dispatcher. The invocation of await()
is a suspending function and will detach the first coroutine from the UI thread, waiting for the completion of the async
-coroutine.
BTW:
You should not use async
and await
in one statement. That makes no sense.
What you really want is to run the queryDevices()
-function from another dispatcher, but not asynchronously from the perspective of coroutines. In this case you should use withContext()
Upvotes: 8