I am learning coroutine with android. and i have curious dispatcher.io the book says like when i use
withcontext(dispatcher.IO)
OR
lifecycleScope(Dispatcher.IO)
it will run on IO.Thread.
but other parts in book say multi-coroutines can run in main thread.
dispatcher.io can run in main-thread(UI Thread in android studio)?
CodePudding user response:
When you use Dispatchers.IO dispatcher, the block, it is applied to, runs in background (worker) Thread. Here are some examples:
Using
withContext(Dispatchers.IO)we can run some long running code or network request in the background(worker) thread. In this case we must mark the functions as suspend:suspend fun doWorkInBackground(): String = withContext(Dispatchers.IO) { // long running code // return some result "Some Result" }Using
launchcoroutine builder. In this case coroutine will be running onDispatchers.IOdispatcher in background thread, and it is not possible to update UI from such coroutine (we need to switch coroutine context toDispatchers.Mainto be able to update UI):lifecycleScope.launch(Dispatchers.IO) { // invoke some suspend functions or execute potentially long running code // to switch context in this case and be able to update UI withContext(Dispatchers.Main) { // updateUI } }
In the second example to avoid switching coroutine context to Dispatchers.Main it is possible to run a coroutine on Dispatchers.Main dispatcher and update UI from there:
lifecycleScope.launch(Dispatchers.Main) {
// call some suspend function, but shouldn't call non-suspend
// long running code from here because it will block the Main Thread and UI may freeze
val result = doWorkInBackground()
// Update UI
textView.text = result
}
