Created
November 16, 2021 16:59
-
-
Save leonardoaramaki/153b27eb5325f878ad4bb7ffe540c2ef to your computer and use it in GitHub Desktop.
Add click debouncing logic to Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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