viewModelScope未取消

时间:2019-09-25 13:20:36

标签: android kotlin android-lifecycle kotlin-coroutines android-viewmodel

观看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 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移到suspend fun start()内部活动所调用的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逻辑。

解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

Kotlin无法为您取消无限操作。您需要在某个地方致电isActive。例如:while(isActive)

答案 1 :(得分:1)

您可以编写自己的LiveData类,而不使用MutableLiveData

这样做时,您可以覆盖显式通知您是否有活动侦听器的方法。

class MyViewModel : ViewModel(){
    val liveData = CustomLiveData(viewModelScope)

    class CustomLiveData(val scope) : LiveData<Int>(){
        private counter = 0
        private lateinit var job: Job

        override fun onActive() {
            job = scope.launch {
                Timber.i("coroutine awake")
                while (true){
                    delay(2_000)
                    Timber.i("another round trip")
                    postValue(counter++)
                }
        }

        override fun onInactive() {
            job.cancel()
        }
    }
}

然后在您的Activity内部,您不再需要显式调用任何开始/暂停,因为LiveData将根据观察者的状态自动开始和取消协程。