Search code examples
androidandroid-architecture-componentsandroid-viewmodelandroid-architecture-navigationandroid-jetpack-navigation

how many view models I have to use in my fragment if I use SharedViewModel to pass data?


I am using navigation component, and I need to pass data back from Fragment B back to Fragment A. I have read from here that I need to use SharedViewModel.

say for example I have a RestaurantListFragment that show list of restaurants. to handle networking and business logic for this fragment I make RestaurantListViewModel .

the second fragment I have is RestaurantDetailFragment. and to handle some actions and business logic in this fragment I create RestaurantDetailViewModel .

now I need to pass data from RestaurantDetailFragment back to RestaurantListFragment, and it is said I need to use SharedViewModel. but now I am confused.

if I use SharedViewModel to pass data, then I will have 2 viewModels in a fragment ? in RestaurantDetailFragment, I will have RestaurantDetailViewModel and XSharedViewModel, and in RestaurantDetailFragment, I will have RestaurantListViewModel and XSharedViewModel ?

so in the the SharedViewModel it only contain the data that need to be passed back to previous fragment ?

or I just need to make make one view model (SharedViewModel) that will serves my two fragments ? (I no longer need to create RestaurantDetailViewModel and RestaurantListViewModel). I am confused.


Solution

  • Both approaches work:

    1. You can use SharedViewModel only for data and methods that are shared between RestaurantDetailFragment and RestaurantListFragment and keep the logic that is only necessary for RestaurantListFragment but not for RestaurantDetailFragment within RestaurantListViewModel and vice versa.

    2. Anyway you can also put all your logic of the RestaurantDetailViewModel and the RestaurantListViewModel inside of the SharedViewModel and get rid of the other 2 ViewModels. While this wouldn't throw any errors, it violates the separation of concerns.