我有一个 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()
}
}
我是否忘记添加一些自定义取消逻辑或缺少其他内容?