协程未启动?基于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
myThrottleClickonce as a property, we keep the samethrottleJobinstance 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 bythrottleFirst, which checks the job state and triggers your action if allowed. - Correct Return Value: The
throttleClicknow properly passes through the throttling function fromthrottleFirst, so you're actually using the logic you built.
内容的提问来源于stack exchange,提问作者GuilhE
相关产品推荐
相关产品推荐

