[英]cancelling a suspend function in kotlin if the same function is called again
I want to cancel the function i created which simply increments a counter value.我想取消我创建的函数,它只是增加一个计数器值。 For example, if the specific function is triggered by click, I only want to display the log for the last uninterrupted click within 2 seconds.
比如具体的功能是点击触发的,我只想显示2秒内最后一次不间断点击的日志。 Basically, i want the function to cancel itself if called again if its ongoing (delay is ongoing).
基本上,如果函数正在进行(延迟正在进行),我希望该函数在再次调用时自行取消。 Is there such thing in kotlin?
kotlin中有这样的东西吗?
val counter = mutableStateOf(0)
suspend fun addCounter(){
counter.value++
delay(2000)
Log.e("click cat","click $counter")
}`
This kind of event processing is usually handled using reactive streams and is often named the debounce operator.这种事件处理通常使用响应式流来处理,并且通常被命名为debounce操作符。 It exists in both ReactiveX ( Debounce ) and in Kotlin flows ( debounce() ).
它存在于 ReactiveX ( Debounce ) 和 Kotlin 流 ( debounce() ) 中。
As you already use coroutines, I suggest going with Kotlin flows.由于您已经使用协程,我建议您使用 Kotlin 流程。 Please see the example below:
请看下面的例子:
private val flow = MutableStateFlow(0)
suspend fun main() = coroutineScope {
launch {
// consumer of events
flow
.debounce(2.seconds)
.collect { println(it) }
}
// producer
delay(100)
addCounter() // 1
delay(500)
addCounter() // 2, ignore 1
delay(500)
addCounter() // 3, ignore 2
delay(2500) // show 3
addCounter() // 4
delay(500)
addCounter() // 5, ignore 4
delay(3000) // show 5
}
fun addCounter() {
flow.value++
}
It shows only 3
and 5
, because all other events were "cancelled" by subsequent events that came too fast.它只显示
3
和5
,因为所有其他事件都被来得太快的后续事件“取消”了。
Suspend function is a function that could be started, paused, and resume.挂起函数是一个可以启动、暂停和恢复的函数。 Suspend functions are only allowed to be called from a coroutine or another suspend function and you can not cancel it in this way.
挂起函数只允许从协程或另一个挂起函数中调用,您不能以这种方式取消它。 Coroutine structured concurrency is the thing that you're looking for.
协程结构化并发是您正在寻找的东西。 You can use a Job to perform your task above.
您可以使用 Job 来执行上述任务。 Now you can cancel the job anytime you need.
现在您可以随时取消作业。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.