Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add click debouncing logic to Jetpack Compose
/**
* Wraps an [onClick] lambda with another one that supports debouncing. The default deboucing time
* is 1000ms.
*
* @return debounced onClick
*/
@Composable
inline fun debounced(crossinline onClick: () -> Unit, debounceTime: Long = 1000L): () -> Unit {
var lastTimeClicked by remember { mutableStateOf(0L) }
val onClickLambda: () -> Unit = {
val now = SystemClock.uptimeMillis()
if (now - lastTimeClicked > debounceTime) {
onClick()
}
lastTimeClicked = now
}
return onClickLambda
}
/**
* The same as [Modifier.clickable] with support to debouncing.
*/
fun Modifier.debouncedClickable(
debounceTime: Long = 1000L,
onClick: () -> Unit
): Modifier {
return this.composed {
val clickable = debounced(debounceTime = debounceTime, onClick = { onClick() })
this.clickable { clickable() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment