An Android Viewmodel can either have the scope/lifespan of either an activity or fragment, but how will this work in a Navigation component?
Considering if I have the following scenario:
MainActivity - Contains the NavHostFragment CustomerListFragment - Starting point for the navigation - On click of any customer in the list, will navigate the CustomerDetailsFragment CustomerDetailsFragment - Contains a tab with 3 fragments: CustomerDetailFragment, CustomerContactFragment and CustomerOrderHistoryFragment CustomerDetailFragment - Display customer general information such as name, age, gender, etc... - Get data from CustomerViewModel CustomerContactFragment - Display customer address, tel, fax, etc - Get data from CustomerViewModel CustomerOrderHistoryFragment - Display customer's order history - Get data from OrderHistoryViewModel
On the scenario above, is it possible to share the same instance of CustomerViewModel for CustomerDetailFragment and CustomerContactFragment?
If I wasn't using the navigation component, I could just make CustomerDetailsFragment an activity and init my viewmodel to that activity but since in Navigation we only have fragments, how can I best achieve this?
I though of:
public class CustomerDetailsFragment extends Fragment { ... CustomerViewModel model = ViewModelProviders.of(this).get(CustomerViewModel .class); ...
but how do I pass this instance of viewmodel to CustomerDetailFragment and CustomerContactFragment?
Or is there a better way to structure the code above to achieve the same result?
ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.It is the main component in the MVVM architecture. ViewModel can be created with activity context or fragment context. When a ViewModel object is created, it is stored inside Activity OR FragmentManager.
Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. Android Jetpack's Navigation component helps you implement navigation, from simple button clicks to more complex patterns, such as app bars and the navigation drawer.
To take full advantage of the Navigation component, your app should use multiple fragments in a single activity. However, activities can still benefit from the Navigation component. Note, however, that your app's UI must be visually broken up across several navigation graphs.
You can use parentFragment
as a store owner. Call this in your Detail
and Contact
fragments.
CustomerViewModel model = ViewModelProviders.of(getParentFragment()).get(CustomerViewModel.class);
your scenario is well supported by ViewModel
.
You just need to get ViewModel with activity scope: ViewModelProviders.of(getActivity).get(...
More info here: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With