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

Cancel all Kotlin coroutines pending jobs on ViewModel's onCleared()

ViewModel 的 onCleared() 中停止 jobs activity 完成后显示 JobCancellationException: Job正在被取消 并保持应用冻结崩溃:

在 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()
        }
    }

内部视图模型:

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)
    }
}