Created
September 11, 2021 17:56
-
-
Save carterhudson/491d97b283aa9a50d4419d8f39773a30 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
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