Files
rider-pro-android-app/app/src/main/java/com/aiosman/ravenow/utils/DebounceUtils.kt
2025-08-27 18:32:51 +08:00

79 lines
2.0 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.aiosman.ravenow.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
/**
* 防抖工具类
* 用于防止用户快速重复点击
*/
object DebounceUtils {
/**
* 防抖点击处理
* @param scope 协程作用域
* @param delayMillis 防抖延迟时间毫秒默认500ms
* @param action 要执行的操作
*/
fun debounceClick(
scope: CoroutineScope,
delayMillis: Long = 500L,
action: () -> Unit
) {
scope.launch {
delay(delayMillis)
action()
}
}
/**
* 带状态检查的防抖点击处理
* @param scope 协程作用域
* @param delayMillis 防抖延迟时间毫秒默认500ms
* @param isProcessing 是否正在处理中的状态
* @param action 要执行的操作
*/
fun debounceClickWithState(
scope: CoroutineScope,
delayMillis: Long = 500L,
isProcessing: AtomicBoolean,
action: () -> Unit
) {
if (isProcessing.get()) {
return
}
isProcessing.set(true)
scope.launch {
delay(delayMillis)
try {
action()
} finally {
isProcessing.set(false)
}
}
}
/**
* 简单的防抖点击处理(无协程)
* @param lastClickTime 上次点击时间
* @param delayMillis 防抖延迟时间毫秒默认500ms
* @param action 要执行的操作
* @return 是否执行了操作
*/
fun simpleDebounceClick(
lastClickTime: Long,
delayMillis: Long = 500L,
action: () -> Unit
): Boolean {
val currentTime = System.currentTimeMillis()
if (currentTime - lastClickTime < delayMillis) {
return false
}
action()
return true
}
}