gpt4 book ai didi

android - viewModelScope 未取消

转载 作者:行者123 更新时间:2023-11-29 18:27:22 25 4
gpt4 key购买 nike

看完Sean's explanation on Android (Google I/O'19)我也试过:

init{
viewModelScope.launch {
Timber.i("coroutine awake")
while (true){
delay(2_000)
Timber.i("another round trip")
}
}
}

不幸的是 onCleared 它在 Activity 被终止时被调用,而不是在它被置于后台时被调用(“当我们离开 Activity 时......”,背景正在“离开”恕我直言 ^^) .
我得到以下输出:

> ---- Activity in Foreground
> 12:41:10.195 TEST: coroutine awake
> 12:41:12.215 TEST: another round trip
> 12:41:14.231 TEST: another round trip
> 12:41:16.245 TEST: another round trip
> 12:41:18.259 TEST: another round trip
> 12:41:20.270 TEST: another round trip
> ----- Activity in Background (on onCleared not fired)
> 12:41:22.283 TEST: another round trip
> 12:41:24.303 TEST: another round trip
> 12:41:26.320 TEST: another round trip
> 12:41:28.353 TEST: another round trip
> 12:41:30.361 TEST: another round trip
> ----- Activity in Foreground
> 12:41:30.369 TEST: coroutine awake

我该如何解决这个问题?

1 - 将代码从 init 移动到由 lifecycleScope.launchWhenStarted 内的 Activity 调用的 suspend fun start()

我得到了相同的结果。我以为 lifecycleScope 会在它进入后台时取消它的子协程,但我用这种方法得到了相同的 Timber 输出。

2 - 将我的 ViewModel 代码更改为:

private lateinit var job: Job

suspend fun startEmitting() {
job = viewModelScope.launch {
Timber.i("coroutine awake")
while (true){
delay(2_000)
Timber.i("another round trip")
}
}
}
fun cancelJob(){
if(job.isActive){
job.cancel()
}
}

并且,在我的 Activity 中:

override fun onResume() {
super.onResume()
lifecycleScope.launch {
viewModel.startEmitting()
}
}
override fun onPause() {
super.onPause()
viewModel.cancelJob()
}

很好,但 viewModelScope 的目的不是为我管理 CoroutineScope 吗?我讨厌这种 cancelJob 逻辑。

处理此问题的最佳方法是什么?

最佳答案

Kotlin 无法为您取消无限操作。您需要在某处调用 isActive。例如:while(isActive)

关于android - viewModelScope 未取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58099407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com