https://kotlinlang.org logo
#compose
Title
# compose
z

ziv kesten

12/28/2021, 1:57 PM
Does anyone have an easy implementation of a debounce button in compose?
s

steelahhh

12/28/2021, 4:33 PM
Not sure if it's the best implementation out there, but we've been using this one quite successfully
Copy code
fun Modifier.delayedClickable(
  delay: Long = 2_000,
  enabled: Boolean = true,
  onClickLabel: String? = null,
  role: Role? = null,
  onClick: () -> Unit
) = composed {
  var lastClickTime by remember { mutableStateOf(0L) }

  Modifier.clickable(
    enabled = enabled,
    onClickLabel = onClickLabel,
    role = role,
    onClick = {
      if (SystemClock.elapsedRealtime() - lastClickTime >= delay) {
        lastClickTime = SystemClock.elapsedRealtime()
        onClick()
      }
    },
  )
}
🙌 1
🔥 2
w

Will Shelor

12/28/2021, 8:39 PM
I will also note that we made our lastClickTime a static object so people couldn't click two separate objects at the same time. It does create a risk of nested throttling, but we also made it log when it happens to make identifying throttled errors easier.
🙏 1
z

ziv kesten

12/29/2021, 3:20 PM
Amazing! thank you very much!!
24 Views