基于此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}"
.../>
ViewModel:
fun myClickListener() = View.OnClickListener { _ ->
throttleClick(clickAction = {
//do things
})
}
BaseViewModel :
protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
throttleFirst(millis, scope = viewModelScope, action = clickAction)
}
但没有任何反应,没有达到 clickAction 。在调试过程中,逐步操作在遇到return { param: T ->
时结束,并且永不调用返回函数(throttleJob?.isCompleted
...代码)。
我在做什么错了?
编辑,在Patrick的帮助下,最终的解决方案是:
ViewModel
private val myThrottleClick = throttleClick(clickAction = {
//do things
})
fun myClickListener() = View.OnClickListener { myThrottleClick(Unit) }
BaseViewModel
protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
return throttleFirst(millis, action = clickAction)
}
答案 0 :(得分:1)
您的throttleFirst
函数会构成一个点击监听器,因此您必须将其存储在点击监听器范围之外的val中。即
val clickListener = throttleFirst { doStuff() }
fun myClickListener() = View.OnClickListener { _ -> clickListener() }
您也许可以完全取消使用myClickListener
函数,而只需在xml中引用clickListener
。