Skip to content

Instantly share code, notes, and snippets.

@leonardoaramaki
Created November 16, 2021 16:59
Show Gist options
  • Save leonardoaramaki/153b27eb5325f878ad4bb7ffe540c2ef to your computer and use it in GitHub Desktop.
Save leonardoaramaki/153b27eb5325f878ad4bb7ffe540c2ef to your computer and use it in GitHub Desktop.
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