Compose Navigation: is there a way to receive a ca...
# compose
d
Compose Navigation: is there a way to receive a callback each time a composable is popped from the backstack?
p
~BackHandler { if (navController.popBackStack()) callback() }~
d
interesting, thanks!
is it possible to define this BackHandler, only at screen composable level, or also at NavHost level?
p
Back press is intercepted by inner most enabled
BackHandler
. Few weeks ago I wrote a blog post about how it works: https://dev.to/pawegio/handling-back-presses-in-jetpack-compose-50d5
d
nice one! I will read it, many thanks
i
Generally, you shouldn't be using a
BackHandler
to forward events to NavController - that code, for instance, doesn't handle the cases where there is no back stack correctly
That's why NavHost and NavController already have their own internal handler that does do that correctly
As we talked about just the other day, what you actually want with
BackHandler
is to be the right dispatch ordering: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1619810151234400?thread_ts=1619801021.217600&cid=CJLTWPH7S
Either after the NavController (i.e., to intercept back before the NavController and do your own action instead - this is what a Back handler inside a destination does) or before the NavController (to do some action when the NavController and it's children have no back handlers enabled)
And if you just want to know when the current destination changes, then you should be reliant solely on the
currentBackStackEntryAsState()
, which will update whenever the destination changes
From within Navigation itself, the way to know when a destination is removed from the stack is via it's ViewModel being cleared. That is literally the only signal you can actually rely on that handles popUpTo, the system back button, and every other case where the destination is not coming back
System back is never enough
p
Thanks @Ian Lake, I forgot to add that
BackHandler
just intercepts system back presses, but there are also different actions that pop the back stack. However, regarding this:
Generally, you shouldn’t be using a 
BackHandler
 to forward events to NavController - that code, for instance, doesn’t handle the cases where there is no back stack correctly
For the sake of code snippet simplicity, I skipped passing it to the view model and handling it in the business logic layer. Is your recommendation to explicitly not pop the back stack this way, because it’s more complicated internally?
i
Correct, you should never be explicitly popping the NavController's stack in your own
BackHandler