Search code examples
androidmvvmrx-javaandroid-viewmodelandroid-architecture-navigation

Navigation with MVVM android


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.


Solution

  • If you were using MVP, P would just call the method on V that triggers navigation.

    The equivalent approach in MVVM would be to have a dedicated observable/listener/callback, if done with RxJava it could be driven by a PublishSubject. This satisfies the one-time requirement. If instead you need to respond to events that may be emitted before you subscribed, you can use a BehaviorSubject<Optional<T>> and create it with createDefault(absent<T>()), trigge it with onNext(Optional.of(navigationObject)) and then let the VM know when navigation occurs, and then the VM can clear it with onNext(absent())

    Alternatively if you want to work it into some all-encompassing redux/mvi-like state, you might have some state class with all the state including some property that indicates to the view to navigate somewhere, upon receiving/acting on this the View would tell the VM it has done so and the VM would set the state to the same as current but without navigation. e.g. (in Kotlin) state = state.copy(navigateToX = false)