基于此post throttleFirst
函数:
fun <T> throttleFirst(
skipMs: Long = 700L,
scope: CoroutineScope = viewModelScope,
action: (T) -> Unit
): (T) -> Unit {
var throttleJob: Job? = null
return { param: T ->
if (throttleJob?.isCompleted != false) {
throttleJob = coroutineScope.launch {
destinationFunction(param)
delay(skipMs)
}
}
}
}
我是这样使用它的:
查看
<Button
android:onClick="@{viewModel.myClickListener}"
.../>
View 模型:
fun myClickListener() = View.OnClickListener { _ ->
throttleClick(clickAction = {
//do things
})
}
基础 View 模型:
protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
throttleFirst(millis, scope = viewModelScope, action = clickAction)
}
但没有任何反应,clickAction 未达到。调试时,当它点击 return { param: T ->
并且返回函数 (throttleJob?.isCompleted
... 代码) 永远不会被调用时,逐步结束.
我做错了什么?
编辑最终的解决方案是:
View 模型
private val myThrottleClick = throttleClick(clickAction = {
//do things
})
fun myClickListener() = View.OnClickListener { myThrottleClick(Unit) }
基础 View 模型
protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
return throttleFirst(millis, action = clickAction)
}
最佳答案
您的 throttleFirst
函数生成点击监听器,因此您必须将其存储在点击监听器范围之外的 val 中。即
val clickListener = throttleFirst { doStuff() }
fun myClickListener() = View.OnClickListener { _ -> clickListener() }
您可以完全取消 myClickListener
函数,只在 xml 中引用 clickListener
。
关于android - 协程没有启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413001/