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()
    }
}
相关推荐
Digitally2 小时前
6 款优质安卓备份提取工具与备份方案
android
恋猫de小郭5 小时前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter
Wellijohn17 小时前
一个 Android 老兵的十年开源路:从 167 star 的滑动控件,到本地优先的 AI Agent
android·人工智能·开源
好的佩奇21 小时前
Dart 之元数据与注解
android·flutter·dart
三少爷的鞋1 天前
很多开发者把物理上的分层,当成了架构
android
FungLeo1 天前
FengCMS · PHP+MySQL 升级实录 · MySQL DDL不能回滚:模型字段结构操作的失败续做
android·mysql·php·工程实践·fengcms
雨白1 天前
Android 建造者模式实战:从 AlertDialog 源码到 TopBar 的两种实现
android
_祝你今天愉快1 天前
Android 高级绘制:[五] 贝塞尔曲线与计算规则
android
FungLeo2 天前
FengCMS · PHP+MySQL 升级实录 · 危险默认值之殇:root/123456、认证码 8888 写进配置加载器
android·mysql·php·安全加固·fengcms
yz_aiks2 天前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux