gpt4 book ai didi

android - 取消 ViewModel 的 onCleared() 上所有待处理的 Kotlin 协程

转载 作者:行者123 更新时间:2023-12-05 00:20:57 27 4
gpt4 key购买 nike

停止职位 的 onCleared() 中查看型号 Activity 结束后显示 JobCancellationException: 作业被取消 并保持应用程序卡住崩溃:

从 Android 中的 ViewModel 的 onCleared() 取消所有 kotlin 协程待处理作业的正确方法是什么

我在 viewModel 中的代码:

private val job = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + job)

uiScope.launch {
try {
repeat(152212000001) { it ->
try {
Log.d("Timer : ", it)
delay(1000)
} catch (e: Exception) {
e.printStackTrace()
}
}
} catch (e: CancellationException) {
e.printStackTrace()
}
}

内部 View 模型:
override fun onCleared() {
job.cancel()
super.onCleared()
}

最佳答案

根据 Easy Coroutines in Android: viewModelScope blog post :

viewModelScope contributes to structured concurrency by adding an extension property to the ViewModel class that automatically cancels its child coroutines when the ViewModel is destroyed.



因此,通过添加对 androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-alpha02 的依赖项(或更高版本),您将能够使用 viewModelScope默认做正确的事:
viewModelScope.launch {
repeat(152212000001) { it ->
Log.d("Timer : ", it)
delay(1000)
}
}

关于android - 取消 ViewModel 的 onCleared() 上所有待处理的 Kotlin 协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com