Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BackHandler only receives backs in super.onBackPressed, but should be received before backstack.goBack #12

Closed
Zhuinden opened this issue Sep 22, 2021 · 2 comments
Labels
bug Something isn't working critical design required

Comments

@Zhuinden
Copy link
Owner

This is actually a major issue in the current examples.

Using backstack.goBack() before super.onBackPressed() means that the dispatcher won't receive it before the backstack going back.

    /**
     * Called when the activity has detected the user's press of the back
     * key. The {@link #getOnBackPressedDispatcher() OnBackPressedDispatcher} will be given a
     * chance to handle the back button before the default behavior of
     * {@link android.app.Activity#onBackPressed()} is invoked.
     *
     * @see #getOnBackPressedDispatcher()
     */
    @Override
    @MainThread
    public void onBackPressed() {
        mOnBackPressedDispatcher.onBackPressed();
    }

Basically, Jetpack team should have probably made onBackPressed final with this new current approach, as the order cannot be correct if you do anything before calling super.onBackPressed.

The solution is to register an always-enabled callback, but the Activity actually tries to close the action bar first instead of finishing.

        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { // always intercept.
            override fun handleOnBackPressed() {
                val topKey = backstack.top<FragmentKey>()
                val fragment = supportFragmentManager.findFragmentByTag(topKey.fragmentTag)
                if (fragment is BackHandler) {
                    val handled = fragment.handleBack()
                    if (handled) {
                        return
                    }
                }
                if (!Navigator.onBackPressed(this@MainActivity)) {
                    finish() // we cannot access Activity.onBackPressed() anymore. RIP
                }
            }
        })

I don't see a way to access Activity.onBackPressed() because super.onBackPressed() would just send to the dispatcher again, causing an infinite loop.

What the heck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working critical design required
Projects
None yet
Development

No branches or pull requests

1 participant