Hello guys. Have small issue. I have nav host with...
# compose
j
Hello guys. Have small issue. I have nav host with
composable
and
bottomSheet
( from accompanist ). In my composable route i set custom BackHandler. But when i navigate from that screen to bottom sheet screen , my bottom sheet screen inherit back handler behaviour from previous screen. Any chance to solve it 😞 ?
i
Well your
composable
destination is still visible underneath the bottom sheet right? Which would mean that the
BackHandler
is still part of composition and still receiving back events unless you make it not enabled (i.e., pass some state that is false when you construct the
BackHandler
)
j
Yeah i made it like that and in my bottomSheet i do this
Copy code
val observer = remember {
    LifecycleEventObserver { _, event ->
        if (event.name == Lifecycle.Event.ON_STOP.name) {
            onSheetClose()
        }
    }
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, observer) {
    lifecycle.addObserver(observer)
    onDispose { lifecycle.removeObserver(observer) }
}
i
When a floating window destination (like your bottom sheet) is on top of your composable destination, the Lifecycle of your composable destination will be
STARTED
, instead of
RESUMED
. You could use that as a signal for if your
BackHandler
should be enabled or not
Yeah, keep in mind in the future world of Predictive Back, you'll want to disable the
BackHandler
if it isn't supposed to intercept back - that way the default NavController one will pick it up (which is important since that is going to matter for running animations)
So really you'd want to use that same kind of DisposableEffect approach to make the current Lifecycle.State exposed as compose state, then use that as input into your BackHandler, e.g.
Copy code
val lifecycle = LocalLifecycleOwner.current.lifecycle
val currentLifecycleState = remember(lifecycle) { mutableStateOf(lifecycle.currentState) }
// Do a DisposableEffect to update currentLifecycleState
BackHandler(currentLifecycleState.isStateAtLeast(Lifecycle.State.RESUMED) {
  // Your back logic
}
j
aha thx a lot Ian for clarification you are best as always! ❤️
i
Hopefully that whole DisposableEffect + LifecycleObserver will go away when this feature request is finished up here soon: https://issuetracker.google.com/235529345
Which will give you a nice way of getting Compose State out of a
Lifecycle