I'm having a slight trouble understanding how coroutine switches threads. If you're switching back to the main thread, and suppose that the main thread is in the middle of doing something, does the coroutine wait for the current code in the main thread to finish before joining (?) the main thread? Or is it usual that the main thread is always available because executing UI-related codes are supposed to be quick?
I tried Bing AI and Google Bard to explain it. They said that withContext(Dispatchers.Main) does not 'join' the main thread, but failed to mention how it exactly affects the main thread for it to be not joining.
This is correct, although it's not a requirement.
withContext
will always do the same thing regardless of whether the target thread is occupied or not. It will enqueue your work on that dispatcher's task queue and await its completion, passing the result to you as the return value ofwithContext
.However, in my experience you should never need to use
withContext(Main)
. Instead launch the coroutine on the main thread (which is the default), and switch to a background thread pool only when you have some blocking or computation-heavy work to do. Retrieve the result as the return value ofwithContext
and then you can use it to update the UI.