Skip to content

Instantly share code, notes, and snippets.

@Ahmed-Sellami
Last active Sep 27, 2021
Embed
What would you like to do?
fun Modifier.dragToReorder(
onDrag: () -> Unit,
onStopDrag: () -> Unit,
): Modifier = composed {
val offsetX = remember { Animatable(0f) }
val offsetY = remember { Animatable(0f) }
pointerInput(Unit) {
// Wrap in a coroutine scope to use suspend functions for touch events and animation.
coroutineScope {
while (true) {
// Wait for a touch down event.
val pointerId = awaitPointerEventScope { awaitFirstDown().id }
// Interrupt any ongoing animation of other items.
offsetX.stop()
offsetY.stop()
// Wait for drag events.
awaitPointerEventScope {
drag(pointerId) { change ->
onDrag()
val horizontalDragOffset = offsetX.value + change.positionChange().x
launch {
offsetX.snapTo(horizontalDragOffset)
}
val verticalDragOffset = offsetY.value + change.positionChange().y
launch {
offsetY.snapTo(verticalDragOffset)
}
// Consume the gesture event, not passed to external
change.consumePositionChange()
}
}
launch {
offsetX.animateTo(0f)
}
launch {
offsetY.animateTo(0f)
onStopDrag()
}
}
}
}
.offset {
// Use the animating offset value here.
IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment