Taz*_*Taz 1 android kotlin kotlin-coroutines
我的代码是这样的。
GlobalScope.launch {
while (true) { // do something.. }
}
Run Code Online (Sandbox Code Playgroud)
有点尴尬。:(
这是正确的方法吗?
您不应该用于GlobalScope创建无限循环。由于您的标签之一提到了 android,假设您正在为其编写程序,因此强烈建议您在/中分别使用LifycycleScope/ 。ViewModelScopeFragment-ActivityViewModel
GlobalScope使用时很容易意外造成资源或内存泄漏。但由于这些作用域(lifecycleScope / viewModelScope)是lifecycle-aware,当特定类(fragment / viewModel)被杀死时,它们将自动取消。您可以使用预构建作用域之一,也可以创建自己的作用域来处理生命周期,viewLifecycleScope而不是使用 GlobalScope 来创建无限循环。您可以通过以下方式使用 viewModelScope:
fun runForever() {
// start a new coroutine in the ViewModel
viewModelScope.launch {
// cancelled when the ViewModel is cleared
while(true) {
delay(1_000)
// do something every second
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6224 次 |
| 最近记录: |