You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

协程未启动?基于throttleFirst的点击节流逻辑无响应排查

Fixing Unresponsive Click with throttleFirst Coroutine Function

Let's walk through why your throttle click wasn't working and how to fix it—there are two key issues in your original code:

1. Missing Return Value in throttleClick

Your BaseViewModel's throttleClick function was declared to return a (Unit) -> Unit function, but you never actually returned the result of throttleFirst. Without that return statement, the function silently returns Unit instead of the throttling logic you need.

2. Not Executing the Returned Throttling Function

In your ViewModel's myClickListener, you called throttleClick(...) but never ran the function it returns. That's why the logic inside throttleFirst's returned lambda never executed—you created the throttler but never triggered it.


Corrected Full Code

First, fix the throttleFirst function (note the typo correction for destinationFunction → action):

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 = scope.launch {
                action(param) // Fixed typo here
                delay(skipMs)
            }
        }
    }
}

Updated BaseViewModel throttleClick:

protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
    // Explicitly return the throttling function from throttleFirst
    return throttleFirst(millis, scope = viewModelScope, action = clickAction)
}

Fixed ViewModel Usage:

// Initialize the throttler once (not every click) to preserve state
private val myThrottleClick = throttleClick(clickAction = { 
    // Your actual click action logic goes here
})

fun myClickListener() = View.OnClickListener {
    // Execute the throttling function to trigger your action
    myThrottleClick(Unit)
}

Why This Works

  • Preserving Throttle State: By initializing myThrottleClick once as a property, we keep the same throttleJob instance across clicks—this is how the throttling remembers if it's still in the cooldown period.
  • Executing the Throttler: Calling myThrottleClick(Unit) runs the lambda returned by throttleFirst, which checks the job state and triggers your action if allowed.
  • Correct Return Value: The throttleClick now properly passes through the throttling function from throttleFirst, so you're actually using the logic you built.

内容的提问来源于stack exchange,提问作者GuilhE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:08:27