Created
November 29, 2023 15:14
-
-
Save j-roskopf/990baa5beef767fbb2fae8cce33e2529 to your computer and use it in GitHub Desktop.
Compose Debounce Click
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
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