简体   繁体   English

安卓。 Kotlin Flow:如何取消倒数计时器?

[英]Android. Kotlin Flow: How to cancel countdown timer?

I have a kotlin flow timer.我有一个 kotlin 流计时器。 Here is my code:这是我的代码:

class CountDownTimer {
    suspend fun startTimer(value: Int, onTick: OnTickCallback, onFinish: OnFinishCallback) {
onTick.invoke(0)
        (1..timerValue)
            .asSequence()
            .asFlow()
            .onEach {
                delay(DELAY)
                onTick.invoke(it)
            }
            .onCompletion {
                onFinish.invoke()
            }
            .cancellable()
            .collect()
}
}

Everything working well, but there are situations when I start a new timer, but the current one has not yet completed.一切正常,但有些情况下我启动了一个新的计时器,但当前的计时器尚未完成。 So I want to cancel the timer if I start a new one.所以如果我开始一个新的计时器,我想取消计时器。 I know that for this I need to get a Job and call a cancel() on it.我知道为此我需要获得一份Job并在其上调用cancel() But I can't create job, because I haven't CoroutineScope .但我无法创造工作,因为我没有CoroutineScope Yes, I could inject the scope in the constructor of my class CountDownTimer, but I need the timer to be attached to the viewModelScope.是的,我可以在我的类 CountDownTimer 的构造函数中注入范围,但我需要将计时器附加到 viewModelScope。

Therefore, I start the timer in the view model in viewModelScope.因此,我在 viewModelScope 的视图模型中启动计时器。

   viewModelScope.launch {
            countDownTimer.startTimer(
                60,
                onTick= { // some logic },
                onFinish= { // some logic }
            )
        }

Now I can get Job inside view model and before start timer cancel() job.现在我可以在视图模型中和开始计时器 cancel() 作业之前获取作业。

But it turns out I have to store the job object in the view model, will it be correct?但事实证明我必须将作业对象存储在视图模型中,这是否正确? Perhaps there is some more automated way to cancel a job.也许有一些更自动化的方式来取消工作。 Or perhaps I'd better inject some other CoroutineScope into my CountDownTimer , then the question is what should the CoroutineScope be?或者我最好在我的CountDownTimer中注入一些其他的CoroutineScope ,那么问题是CoroutineScope应该是什么?

Please, help me.请帮我。

viewModelScope.launch {} is a job. viewModelScope.launch {}是一项工作。 You can save it into a variable and cancel it anytime.您可以将其保存到变量中并随时取消它。 It is ok to store it in a viewmodel .可以将其存储在viewmodel中。

val job = viewModelScope.launch { ... }

job.cancel()

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

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