看完后Sean 对 Android 的解释 (Google I/O'19) https://youtu.be/BOHK_w09pVA?t=1425我也尝试过同样的操作:
init{
viewModelScope.launch {
Timber.i("coroutine awake")
while (true){
delay(2_000)
Timber.i("another round trip")
}
}
}
很遗憾onCleared
当活动被杀死时会调用它,但当它被放入后台时不会调用它(“当我们离开活动时......”,背景是“移开”恕我直言^^)。
我得到以下输出:
> ---- 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
to a suspend fun start()
由 a 内的活动调用lifecycleScope.launchWhenStarted
?
我得到同样的结果。我想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()
}
}
并且,在我的活动中:
override fun onResume() {
super.onResume()
lifecycleScope.launch {
viewModel.startEmitting()
}
}
override fun onPause() {
super.onPause()
viewModel.cancelJob()
}
嗯,它有效,但不是viewModelScope
目的是为了管理CoroutineScope
为我?我讨厌这个 cancelJob 逻辑。
处理这个问题的最佳方法是什么?