I know we have `BackHandler` in CMP now. But how c...
# multiplatform
k
I know we have
BackHandler
in CMP now. But how can I call the back press handler manually, for example, on a button click? On Android I can simply use
LocalOnBackPressedDispatcherOwner.current
and I can be sure that the correct back press logic will work, like calling a
BackHandler
if someone installed it, or falling back to nav controller if not (I’m on Nav2). Is there something similar in CMP?
v
You should migrate to
navigationevent
and use
LocalNavigationEventDispatcherOwner
. I've created a helper function and then call
DirectNavigationEventInput::backCompleted
to go back.
Copy code
@Composable
fun rememberNavigationEventInput(): DirectNavigationEventInput {
    val input = remember { DirectNavigationEventInput() }
    LocalNavigationEventDispatcherOwner.current?.navigationEventDispatcher?.let { dispatcher ->
        DisposableEffect(dispatcher) {
            dispatcher.addInput(input)
            onDispose { dispatcher.removeInput(input) }
        }
    }
    return input
}
k
@Vilgot Fredenberg thanks! Couple of questions: • I assume navigationevent doesn’t depend on navigation library version? Can I use it with navigation 2? • Do I need to provide navigation event dispatcher or is it coming out of the box with CMP? seems like I need to add an extra dependency at least.
v
• I don't know exactly how it's all wired up with nav 2 and CMP (I target Android and use nav3), but
LocalOnBackPressedDispatcherOwner
, for example, just forwards stuff to
LocalNavigationEventDispatcherOwner
. Briefly looking through compose-multiplatform-core, I can see a lot of references to it as well. • It should be set up by compose for you (
ComponentActivity
in the case of Android) and you should therefore already (transitively) depend upon it