androidandroid-architecture-navigationandroid-navigationandroid-bundle

How many times should I add cityName to Bundle in Navigation Component with 4 fragments?


I have implemented Navigation Component with 4 fragments:

F1 -> F2 -> F3 -> F4

To navigate from F1 -> F2, I use :

val bundle = bundleOf("cityName" to cityName)
findNavController().navigate(R.id.second_fragment, bundle)

Now, I want to propagate the "cityName" all the way to F4. Is it necessary to do the same thing also when navigation from F2 -> F3 and F3 -> F4, or is it enough to do it only once, as I already did?


Solution

  • If you use arguments, you need to propagate them from one fragment to another, because each fragment can have different set of arguments. You can improve this by using Safe Args plugin.

    Alternative 1

    In case of single activity it's easy to define shared view model to control common ui parts of your app (app bar title, for example)

    interface HostViewModel {
        
        val screenTitle: LiveData<String>
    
        fun setScreenTitle(title: String)
    }
    

    Alternative 2

    You can create nested graph for your flow (F1->...->F4) and tie destination view model to it