Skip to content

Instantly share code, notes, and snippets.

@alexvanyo
Last active January 5, 2026 08:27
Show Gist options
  • Select an option

  • Save alexvanyo/332ee69d12fedabc71804aa7d22ef509 to your computer and use it in GitHub Desktop.

Select an option

Save alexvanyo/332ee69d12fedabc71804aa7d22ef509 to your computer and use it in GitHub Desktop.
A Modifier to track all touch inputs on a Composable
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
/**
* A [Modifier] that tracks all input, and calls [block] every time input is received.
*/
private fun Modifier.notifyInput(block: () -> Unit): Modifier =
composed {
val currentBlock by rememberUpdatedState(block)
pointerInput(Unit) {
while (currentCoroutineContext().isActive) {
awaitPointerEventScope {
awaitPointerEvent(PointerEventPass.Initial)
currentBlock()
}
}
}
}
@rohanbattery
Copy link

/**
 * Updated the code to use the Modifier.Node
 **/
private fun Modifier.notifyInput(block: () -> Unit): Modifier =
    this.then(NotifyInputElement(block))

private data class NotifyInputElement(
    private val block: () -> Unit
) : ModifierNodeElement<NotifyInputNode>() {
    override fun create(): NotifyInputNode = NotifyInputNode(block)

    override fun update(node: NotifyInputNode) {
        node.block = block
    }
}

private class NotifyInputNode(
    var block: () -> Unit
) : Modifier.Node(), PointerInputModifierNode {
    override fun onCancelPointerInput() {
        // Nothing to do
    }

    override fun onPointerEvent(
        pointerEvent: PointerEvent,
        pass: PointerEventPass,
        bounds: IntSize
    ) {
        if (pass == PointerEventPass.Initial) {
            block()
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment