Compose 封装 - 点击防抖

一、概念

|-------------|-------------------------------------------------------------------------------|
| 简单场景(如登录按钮) | 使用标记,实现成本低。定义一个布尔状态 isLoading,业务代码开始时若为 true 则直接return,在成功后或finally中设为 false。 |
| 搜索框 | 延迟执行。 |
| 需立即反馈 | 一段时间内只执行一次。 |

二、基于时长

2.1 封装为Modifier

Kotlin 复制代码
/**
 * 双击防抖
 */
fun Modifier.clickableDebounce(
    duration: Long = 5000L,
    onClick: () -> Unit
) = composed {
    var lastClick by remember { mutableLongStateOf(0L) }
    this.then(
        Modifier.clickable(
            onClick = {
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastClick >= duration) {
                    onClick()
                    lastClick = currentTime
                }
            },
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        )
    )
}

2.2 封装为函数

适用于自带点击回调的组件如Button。

Kotlin 复制代码
/**
 * 双击防抖(适用于自带点击回调的组件如Button)
 */
inline fun onClickDebounce (
    lastClickTime: Long,
    onLastClickTimeChange: (Long) -> Unit,
    duration: Long = 5000L,
    onClick: () -> Unit,
) {
    val currentTime = System.currentTimeMillis()
    if (currentTime - lastClickTime >= duration) {
        onLastClickTimeChange(currentTime)
        onClick()
    }
}
相关推荐
乾坤一气杀21 小时前
OkHttp3 内部工作原理时序图
android
一起搞IT吧1 天前
相机拍照无响应问题分析一:【MEMORY_NOT_ENOUGH导致】持续快拍,一会儿无法拍照了
android·c++·数码相机·智能手机
是店小二呀1 天前
【MySQL】MySQL 从安装到理解
android·mysql·adb
we1less1 天前
[audio] threadLoop_write 到 audio-hal 分析
android
冬奇Lab1 天前
一次必现ANR问题的深度分析与解决之旅:当NestedScrollView遇上VelocityTracker
android·性能优化·debug
三少爷的鞋1 天前
2025 技术总结:我把技术重新结构化的一年
android
叶羽西1 天前
查Google Android某个子仓库的修改情况
android
a176029317571 天前
3DS模拟器 Azahar模拟器最新版 安卓汉化中文版+PC版附3DS中文游戏资源全集+3DS密匙key和字库
android·游戏
山山而川 潺潺如镜1 天前
python防止程序多开,但程序运行脚本
android·开发语言·python