[英]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()
}
}
I suppose your way of approach is actually correct.我想你的方法实际上是正确的。 What is the exact problem?确切的问题是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.