【发布时间】:2021-01-04 06:31:49
【问题描述】:
我有一个 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( 私人 val dispatcherProvider: DispatcherProvider ) : ViewModel(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = job + dispatcherProvider.provideUIContext()
private val job = SupervisorJob()
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
我是否忘记添加一些自定义取消逻辑或遗漏其他内容?
【问题讨论】:
标签: kotlin kotlin-coroutines android-viewmodel kotlin-flow