Is it possible to use BackHandler to intercept bac...
# compose
m
Is it possible to use BackHandler to intercept back event for analytics purposes, but not handle it ?
i
No, as per its name, a BackHandler must handle the back action. Generally you'd want to hook analytics into what state is actually being changed (e.g.,
onDestroy
of the activity, current destination changing in Navigation Compose, etc.) rather than trying to hook into the gesture handling itself
m
ya i see. I need to send some event when the user abort the flow on a specific screen. I got it. thanks!
s
I tried this one and worked fine (you may want to call
rememberUpdatedState
on
onBack
)
Copy code
@Composable
fun InterceptBackPress(onBack: () -> Unit) {
    val lifecycleOwner = LocalLifecycleOwner.current
    val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
    
    DisposableEffect(backDispatcher) {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                onBack()
                isEnabled = false
                backDispatcher?.onBackPressed()
            }
        }

        backDispatcher?.addCallback(lifecycleOwner, callback)

        onDispose(callback::remove)
    }
}
i
Absolutely please never, ever do that. You're completely breaking the ahead of time model and predictive back gesture