Restricting back navigation from nested nav graph

13 Views Asked by At

I will give simplified version of my issue. I have 2 fragments. MainFrag, LoginFrag. Both are contained inside their seperate nav graph. mainGraph, loginGraph respectively (please excuse naming convention). So my default graph is mainGraph, and loginGraph is nested inside mainGraph. When app is opened, if user is not logged in, loginGraph opens.

Problem Statement - When I press backButton from loginFrag, it navigates back to parent (mainGraph - MainFrag). I tried to pop the parent graph, before navigating to loginGraph. So here the backNavigation is restricted from loginFrag. But then I cannot navigate back to the parent graph (mainGraph) after successful login.

mainGraph (MainFrag, with other frags mainGraph (MainFrag, with other frags

loginGraph (LoginFrag, with other Frags loginGraph (LoginFrag, with other Frags)

This is my current workaround. I restricted the backNavigation from loginFrag. Is their any best practice for this issue.

        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    Timber.d("handleOnBackPressed: backButtonClicked")
                }
            })
        

I call this inside onViewCreated()

0

There are 0 best solutions below