我正在使用 android 學習協程。我有好奇的 dispatcher.io 這本書說的就像我使用的時候
帶有背景關系(調度程式.IO)
或者
生命周期范圍(Dispatcher.IO)
它將在 IO.Thread 上運行。
但是書中的其他部分說多協程可以在主執行緒中運行。
dispatcher.io 可以在主執行緒中運行(android studio 中的 UI 執行緒)?
uj5u.com熱心網友回復:
當您使用Dispatchers.IO調度程式時,它所應用的塊在后臺 (worker) 中運行Thread。這里有些例子:
使用
withContext(Dispatchers.IO)我們可以在后臺(作業者)執行緒中運行一些長時間運行的代碼或網路請求。在這種情況下,我們必須將函式標記為掛起:suspend fun doWorkInBackground(): String = withContext(Dispatchers.IO) { // long running code // return some result "Some Result" }使用
launch協程構建器。在這種情況下,協程將Dispatchers.IO在后臺執行緒的調度程式上運行,并且無法從此類協程更新 UI(我們需要切換協程背景關系Dispatchers.Main才能更新 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 } }
在第二個示例中,為了避免切換協程背景關系,Dispatchers.Main可以在Dispatchers.Main調度程式上運行協程并從那里更新 UI:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405909.html
標籤:
