0

我有一个 UseCase 类,其方法返回 Flow

fun startTimeTicker(startTime: Long) = flow {
    val countdownStart = System.currentTimeMillis()
    for (currentTime in countdownStart..startTime step ONE_SECOND_MILLIS) {
        .... irrelevant ...
        emit("Some String")
        delay(ONE_SECOND_MILLIS)
    }
}

我正在像这样在 ViewModel 中收集发布日期

private fun startCollecting(startTime: Long) = launch {
    matchStartTimerUseCase.startTimeTicker(startTime).collect {
        _startTimeCountdown.postValue(it)
    }
}

我的片段正在观察 LiveData 并显示值。在我离开屏幕之前,它会按预期工作。正如launch用 ViewModel 的 coroutineScope 调用的那样,它不应该被取消并且不再发出值吗?

ViewModel 的范围在 BaseViewModel 中实现,我的 ViewModel 扩展如下:

抽象类 BaseViewModel(private val dispatcherProvider: DispatcherProvider) : ViewModel(), CoroutineScope {

override val coroutineContext: CoroutineContext
    get() = job + dispatcherProvider.provideUIContext()

private val job = SupervisorJob()

override fun onCleared() {
    super.onCleared()
    job.cancel()
}

}

我是否忘记添加一些自定义取消逻辑或缺少其他内容?

4

1 回答 1

1

如果您的 ViewModel 范围是 Activity 的生命周期 ViewModelProvider(requireActivity()).get(YOUR_VIEWMODEL::class.java),那么onCleared除非您的 Activity 被销毁,否则不会被调用,但不会被旋转更改。

首先,确保 onCleared() 被调用,如果它没有被调用,你可以调用它任何 Fragment 或 Activity 的生命周期方法。

于 2020-09-17T11:22:23.780 回答