google / accompanist

A collection of extension libraries for Jetpack Compose
https://google.github.io/accompanist
Apache License 2.0
7.31k stars 592 forks source link

[Navigation Material] BackHandler is not triggered after Activity stop+start #1760

Closed david-tixr closed 4 months ago

david-tixr commented 4 months ago

Description

BackHandlers declared inside a bottomSheet destination don't always work. The first time they come into the composition, pressing back will correctly trigger them. But after the Activity is stopped (backgrounded) then started again (foregrounded), pressing back doesn't trigger the BackHandler: it pops the back stack instead.

Steps to reproduce

I have forked the repo and added just a few lines to repro in the sample app: https://github.com/google/accompanist/compare/main...david-tixr:bug/bottom-sheet-back-handler

  1. Checkout the bug/bottom-sheet-back-handler branch in my fork
  2. Run the sample app
  3. Open the "Navigation: Bottom Sheets" sample
  4. Click "Show sheet!"
  5. Press back: the toast appears with "Back pressed!"
  6. Background, then foreground the app
  7. Press back again

EXPECTED: the toast should appear ACTUAL: the toast doesn't appear, the sheet is closed instead

Additional context

I've spent some time debugging this issue. A pivotal point is to observe with debug breakpoints how androidx.activity.OnBackPressedDispatcher$addCancellableCallback gets called.

At first, this is the sequence:

  1. The callback from NavHostController (upon clicking "Navigation: Bottom Sheets")
  2. The one from BottomSheetNavigator (upon clicking "Show sheet!")
  3. My callback from BottomSheetNavSample (right after)

But when I background and foreground the app, this same method gets called with a different (wrong) order:

  1. The callback from NavHostController
  2. My callback from BottomSheetNavSample
  3. The one from BottomSheetNavigator

On a back press, the callback that's been added last is the one that gets called: in this case, the one from BottomSheetNavigator. The question is: why do these callbacks get added back in the wrong order?

ianhanniballake commented 4 months ago

With the release of Compose Material 1.7.0-alpha04, the Material team has added a new artifact: androidx.compose.material:material-navigation, which fully replaces Accompanist Navigation Material.

As such, we are closing all issues here on Accompanist and will be fully deprecating Accompanist Navigation Material in an upcoming release.

A number of issues were fixed as part of the migration, but if you're still seeing an issue, please file an issue with a sample project that reproduces your issue and the Material team will take a look.