Skip to content

Instantly share code, notes, and snippets.

@carterhudson
Created September 11, 2021 17:56
Show Gist options
  • Save carterhudson/491d97b283aa9a50d4419d8f39773a30 to your computer and use it in GitHub Desktop.
Save carterhudson/491d97b283aa9a50d4419d8f39773a30 to your computer and use it in GitHub Desktop.
fun Modifier.repeatingClickable(
interactionSource: MutableInteractionSource,
enabled: Boolean,
maxDelayMillis: Long = 1000,
minDelayMillis: Long = 5,
delayDecayFactor: Float = .20f,
onClick: () -> Unit
): Modifier = composed {
val currentClickListener by rememberUpdatedState(onClick)
pointerInput(interactionSource, enabled) {
forEachGesture {
coroutineScope {
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false)
// Create a down press interaction
val downPress = PressInteraction.Press(down.position)
val heldButtonJob = launch {
// Send the press through the interaction source
interactionSource.emit(downPress)
var currentDelayMillis = maxDelayMillis
while (enabled && down.pressed) {
currentClickListener()
delay(currentDelayMillis)
val nextMillis = currentDelayMillis - (currentDelayMillis * delayDecayFactor)
currentDelayMillis = nextMillis.toLong().coerceAtLeast(minDelayMillis)
}
}
val up = waitForUpOrCancellation()
heldButtonJob.cancel()
// Determine whether a cancel or release occurred, and create the interaction
val releaseOrCancel = when (up) {
null -> PressInteraction.Cancel(downPress)
else -> PressInteraction.Release(downPress)
}
launch {
// Send the result through the interaction source
interactionSource.emit(releaseOrCancel)
}
}
}
}
}.indication(interactionSource, rememberRipple())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment