I've been using the new new Navigation-API in Jetpack and I've come across a problem that I can't find a satisfactory solution to.
Basically the app I'm creating has a large number of different fragments. Most of the fragments talk to a backend and when they do they can discover that their session has timed out. When this occurs I want to go to the login-fragment. The only way I've been able to do this is to create an action for every fragment with the destination pointing to the login screen. This is a lot of boiler plate that I would rather avoid. Is there a simpler way to do this?
For this use case you can use global action. To create global action, select the desired destination in navigation graph. Right click and in the menu select ‘Add action’ and click on ‘Global’, this will create a global action inside your navigation graph root element:
<action android:id="@+id/action_global_signInFragment" app:destination="@id/signInFragment"/>
Now you can use global actions by calling navigation() method and passing it the id of the desired global action:
NavHostFragment.findNavController(this).navigate(R.id.action_global_signInFragment)
https://developer.android.com/topic/libraries/architecture/navigation/navigation-global-action
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With