简体   繁体   English

Android 协程视图模型范围取消

[英]Android coroutine viewmodelscope cancel

I have seen a lot of examples that use a job as a way to cancel coroutines when viewmodel is destroyed.我已经看到了很多使用作业作为在视图模型被破坏时取消协程的方法的示例。

class SetupViewModel : ViewModel() {

    private val completableJob = Job()
    private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)

    override fun onCleared() {
        super.onCleared()
        completableJob.cancel()
    }
}

The strange thing for me is no one seems to be using coroutineScope to do that.对我来说奇怪的是似乎没有人使用 coroutineScope 来做到这一点。 I think that should be easier and has less code.我认为这应该更容易并且代码更少。 Any idea?任何想法?

class SetupViewModel : ViewModel() {
    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    override fun onCleared() {
        super.onCleared()
        coroutineScope.cancel()
    }
}

Easy way you can use lifecycle-viewmodel-ktx and use viewModelScope already defined by library and you don't need override onCleared , read more here您可以使用简单的方法来使用lifecycle-viewmodel-ktx并使用库已经定义的viewModelScope并且您不需要覆盖onCleared ,请在此处阅读更多信息

I suppose your way of approach is actually correct.我想你的方法实际上是正确的。 What is the exact problem?确切的问题是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM