Skip to content

Instantly share code, notes, and snippets.

@j-roskopf
Created November 29, 2023 15:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save j-roskopf/990baa5beef767fbb2fae8cce33e2529 to your computer and use it in GitHub Desktop.
Compose Debounce Click
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import kotlinx.datetime.Clock
private const val DEBOUNCE_TIME_MILLIS = 1000L
internal interface EventProcessor {
fun processEvent(event: () -> Unit)
companion object {
val buttonClickMap = mutableMapOf<String, EventProcessor>()
}
}
private class EventProcessorImpl : EventProcessor {
private val now: Long
get() = Clock.System.now().toEpochMilliseconds()
private var lastEventTimeMs: Long = 0
override fun processEvent(event: () -> Unit) {
if (now - lastEventTimeMs >= DEBOUNCE_TIME_MILLIS) {
event.invoke()
}
lastEventTimeMs = now
}
}
internal fun EventProcessor.Companion.get(id: String): EventProcessor {
return buttonClickMap.getOrPut(
id
) {
EventProcessorImpl()
}
}
@Composable
fun debouncedClick(
id: String = randomUUID(),
onClick: () -> Unit,
): () -> Unit {
val multipleEventsCutter = remember { EventProcessor.get(id) }
val newOnClick: () -> Unit = {
multipleEventsCutter.processEvent { onClick() }
}
return newOnClick
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment