我使用GlobalScopewith runBlockingin MainActivity,但我不使用 flow just suspend 功能。我想GlobalScope從 Coroutines更改為其他 Scope。
用例
class UpdateNotificationListItemUseCase @Inject constructor(private val notificationDao: NotificationDao): BaseUpdateBooleanUseCase<Int, Boolean, Boolean, Boolean, Unit>() {
override suspend fun create(itemId: Int, isRead: Boolean, isArchived: Boolean, isAccepted: Boolean){
notificationDao.updateBooleans(itemId, isRead, isArchived, isAccepted)
}
}
主要活動
val job = GlobalScope.launch { vm.getIdWithUpdate() }
runBlocking {
job.join()
}
主視圖模型
suspend fun getIdWithUpdate() {
var id = ""
id = notificationAppSessionStorage.getString(
notificationAppSessionStorage.getIncomingKeyValueStorage(),
""
)
if (id != "") {
updateNotificationListItemUseCase.build(id.toInt(), true, false, false)
}
}
}
我的提議:
我已閱讀檔案https://developer.android.com/kotlin/coroutines/coroutines-best-practices
val IODispatcher: CoroutineDispatcher = Dispatchers.IO
val externalScope: CoroutineScope = CoroutineScope(IODispatcher)
suspend {
externalScope.launch(IODispatcher) {
vm.getIdWithUpdate()
}.join()
}
第二種選擇,但在這里我不等到作業完成
suspend {
withContext(Dispatchers.IO) {
vm.getIdWithUpdate()
}
}
你怎么看待這件事?它不提供給 ANR,我也阻止執行緒。
uj5u.com熱心網友回復:
您可以使用lifecycleScopeinMainActivity代替GlobalScope來啟動協程:
lifecycleScope.launch {
vm.getIdWithUpdate() // calling suspend function
// here suspend function `vm.getIdWithUpdate()` finished execution
// ... do something after suspend function is done
}
要使用lifecycleScope添加依賴項:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:$2.4.0'
GlobalScope強烈建議不要使用。并且不需要呼叫job.join(),呼叫后可以在協程構建塊中做一些事情vm.getIdWithUpdate(),例如更新UI。這個協程使用Dispatchers.Main背景關系運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/409897.html
標籤:
