简体   繁体   English

Kotlin 协程 Flow 未取消

[英]Kotlin coroutines Flow is not canceled

I have a UseCase class with method that returns Flow我有一个 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)
    }
}

I'm collecting emmitted date in ViewModel like this我正在像这样在 ViewModel 中收集发送日期

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

and my fragment is observing LiveData and displaying values.我的片段正在观察 LiveData 并显示值。 It works as expected until the time I leave the screen.它按预期工作,直到我离开屏幕。 As launch is called with coroutineScope of ViewModel shouldn't it get canceled and not emit values anymore?当使用 ViewModel 的 coroutineScope 调用launch ,它不应该被取消并且不再发出值吗?

Scope of ViewModel is implemented in BaseViewModel from which my ViewModel extends like this: ViewModel 的范围在 BaseViewModel 中实现,我的 ViewModel 从中扩展如下:

abstract class BaseViewModel( private val dispatcherProvider: DispatcherProvider ) : ViewModel(), CoroutineScope {抽象类 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()
}

} }

Am I forgetting to add some custom cancellation logic or missing something other?我是否忘记添加一些自定义取消逻辑或缺少其他内容?

If scope your ViewModel is Activity's life cycle ViewModelProvider(requireActivity()).get(YOUR_VIEWMODEL::class.java) then onCleared won't be called unless your Activity gets destroyed, but not with rotation changes.如果您的 ViewModel 的范围是 Activity 的生命周期ViewModelProvider(requireActivity()).get(YOUR_VIEWMODEL::class.java)然后onCleared将不会被调用,除非您的 Activity 被销毁,但不会调用轮换更改。

First, make sure that onCleared() is called, if it's not called you can call it any life cycle method of Fragment or Activity.首先,确保 onCleared() 被调用,如果它没有被调用,你可以调用它任何 Fragment 或 Activity 的生命周期方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM