Created
January 28, 2025 14:27
-
-
Save kevinmcampos/b248812b0d146f1adad0da9cb3e31dcd to your computer and use it in GitHub Desktop.
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 | |
internal const val DEFAULT_DEBOUNCE_TIME = 1000L | |
private class EventProcessor { | |
private val now: Long | |
get() = Clock.System.now().toEpochMilliseconds() | |
private var lastEventTimeMs: Long = 0 | |
fun processEvent(debounceTimeMillis: Long, event: () -> Unit) { | |
if (debounceTimeMillis <= 0) return event() | |
if (now - lastEventTimeMs >= debounceTimeMillis) { | |
event() | |
lastEventTimeMs = now | |
} | |
} | |
} | |
@Composable | |
fun debouncedLambda(debounceTimeMillis: Long = DEFAULT_DEBOUNCE_TIME, onClick: () -> Unit): () -> Unit { | |
val eventProcessor = remember { EventProcessor() } | |
return { | |
eventProcessor.processEvent(debounceTimeMillis) { onClick() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment