Activity 完成后,在ViewModel的onCleared()中停止作业会显示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()
}
}
ViewModel 内部:
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/