协程没有启动?

Coroutine doens't start?

基于此 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)
}

您的 throttleFirst 函数生成点击监听器,因此您必须将其存储在点击监听器范围之外的 val 中。即

val clickListener = throttleFirst { doStuff() }

fun myClickListener() = View.OnClickListener { _ -> clickListener() }

您可以完全取消 myClickListener 函数,而只引用 xml 中的 clickListener