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?