Hi i am trying to implement a compose `debounce` f...
# compose
t
Hi i am trying to implement a compose
debounce
for clickables and have this
Modifier
extension...
😉 1
👇 1
🧵 1
Copy code
inline fun Modifier.debounceClickable(
    enabled: Boolean = true,
    onClickLabel: String? = null,
    role: Role? = null,
    debounceInterval: Long = 400L,
    crossinline onClick: () -> Unit,
): Modifier = composed(
    inspectorInfo = debugInspectorInfo {
        name = "debounceClickable"
        properties["enabled"] = enabled
        properties["onClickLabel"] = onClickLabel
        properties["role"] = role
        properties["onClick"] = onClick()
    }
) {
    var lastClickTime by remember { mutableStateOf(0L) }
    val currentTime = Instant.now().toEpochMilli()

    clickable(
        enabled = enabled,
        onClickLabel = onClickLabel,
        onClick = {
            if ((currentTime - lastClickTime) < debounceInterval) doNothing()
            else {
                onClick()
                lastClickTime = currentTime
            }
        },
        role = role,
        indication = LocalIndication.current,
        interactionSource = remember { MutableInteractionSource() }
    )
}
what can i employ for
IconButtons
though? as they use their own Modifier clickable
Copy code
@Composable
fun IconButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    colors: IconButtonColors = IconButtonDefaults.iconButtonColors(),
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable () -> Unit
) {
    Box(
        modifier =
        modifier
            .minimumTouchTargetSize()
            .size(IconButtonTokens.StateLayerSize)
            .background(color = colors.containerColor(enabled).value)
            .clickable(
                onClick = onClick,
                enabled = enabled,
                role = Role.Button,
                interactionSource = interactionSource,
                indication = rememberRipple(
                    bounded = false,
                    radius = IconButtonTokens.StateLayerSize / 2
                )
            ),
        contentAlignment = Alignment.Center
    ) {
        val contentColor = colors.contentColor(enabled).value
        CompositionLocalProvider(LocalContentColor provides contentColor, content = content)
    }
}
z
You could use a similar approach, but instead return the debounced click lambda instead of a specific
Modifier
. That way you can specify it to any composable that accepts onClick, etc.
564 Views