Is it possible to use BackHandler to intercept back event for analytics purposes, but not handle it ?
i
Ian Lake
10/31/2022, 5:12 PM
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
myanmarking
10/31/2022, 5:14 PM
ya i see. I need to send some event when the user abort the flow on a specific screen. I got it. thanks!
s
ste
10/31/2022, 5:36 PM
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
Ian Lake
10/31/2022, 5:38 PM
Absolutely please never, ever do that. You're completely breaking the ahead of time model and predictive back gesture