I have an app using Androids ViewModel class and Navigation Component for navigating between fragments. How would I handle navigation from the ViewModel? I am using RxJava and I was thinking of having the Fragments listen for navigation events and then trigger navigation that way. What is the normal way to handle this? I am also using Dagger for dependency injection if that helps.
Per the LiveData with SnackBar, Navigation, and other events blog post:
Some data should be consumed only once, like a Snackbar message, a navigation event or a dialog trigger.
Instead of trying to solve this with libraries or extensions to the Architecture Components, it should be faced as a design problem. We recommend you treat your events as part of your state.
They detail the use of a SingleLiveEvent class which ensures that each Navigation event is only received once by an Observer (i.e., your Fragment that has access to your NavController
).
The other alternative is to use an 'Event wrapper' model where the event must be explicitly marked as handled.