I also read that article.
As my understand:
sealed class NavigationCommand {
data class To(val directions: NavDirections): NavigationCommand()
object Back: NavigationCommand()
data class BackTo(val destinationId: Int): NavigationCommand()
object ToRoot: NavigationCommand()
}
That provides all actions
can do in one situation.
For example your graph have some fragments: S -> A -> B -> C -> D
.
Now, you are in the Fragment C
.
You may want to do one of these actions:
- I want to navigate to D -> sendCommand:
NavigationCommand.To(R.id.Id_Of_D)
- I want to navigate to the previous screen: -> sendCommand:
NavigationCommand.Back
- I want to navigate back to
A
-> sendCommand: NavigationCommand.BackTo(R.id.Id_Of_A)
- I want to navigate back to the root of the current graph: -> sendCommand:
NavigationCommand.ToRoot)
That it is.
There are commands you need to send from view model, after that the view model will fire that event to the live data.
Next, the MOST IMPORTANT HERE - How is that event is comsumed
.
You have to take a look at the BaseFragment
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
vm?.navigationCommands?.observe { command ->
when (command) {
is NavigationCommand.To ->
findNavController().navigate(command.directions)
…
In the article, there is small implement.
But for full implementation, it will look like this one:
BaseFragment.kt
open class BaseFragment : Fragment() {
open val baseViewModel: BaseViewModel? = null
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
baseViewModel?.navigationCommands?.observeEventNonNull(viewLifecycleOwner) { command ->
val navController = findNavController()
when (command) {
is NavigationCommand.To -> navController.navigate(command.directions)
NavigationCommand.Back -> navController.popBackStack()
is NavigationCommand.BackTo ->
navController.popBackStack(command.destinationId, false)
NavigationCommand.ToRoot ->
navController.popBackStack(navController.graph.startDestination, false)
}
}
}
}
So, till now, you will see, all the events we post in the view model to navigationCommands
is handled here.
Have a nice coding!