Home > Blockchain >  Android App pass data from ViewModel to ViewModel
Android App pass data from ViewModel to ViewModel

Time:12-22

I have a restaurant app with two main fragments each with their own viewmodels -

LiveList fragment & viewmodel that retrieves a list of restaurants from the internet and displays them in a recyclerView.

SavedList fragment & viewmodel that displays the saved restaurants from a database and deals with all the database interactions

What I want to do is when the user clicks the star next to each restaurant in the LiveList for that restaurant to be added to my SavedList database.

Can I:

1- simply call a reference of SavedListViewModel.addRestaurant from LiveListViewModel ?

2- need to change to a shared ViewModel approach?

3- make the addRestaurant an interface that the LiveList can access?

4- let SavedListViewModel observe a piece of Livedata from LiveListViewModel and tie that Livedata to the selected restaurant?

5- none of these approaches viable?

CodePudding user response:

Make a shared view model in activity scope.

viewModels gives you the ViewModel instance scoped to the current fragment. This will be different for different fragments.

activityViewModels gives you the ViewModel instance scoped to the current activity. Therefore the instance will remain the same across multiple fragments in the same activity.

https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel#4

  • Related