2

I have a ViewPager, where I show multiple instances of PetFragment. To create a new instance of a PetFragment, I call PetFragment.newInstance(petId).

I want a separate ViewModel instance for each petId. But ViewModelProvider.Factory#create() only takes a Class<T> as a parameter. How do I achieve this?

ZakTaccardi
  • 12,212
  • 15
  • 59
  • 107
  • is your problem solved ? . I too have same problem . https://stackoverflow.com/questions/54862222/viewpager-with-viewmodel-and-live-data-all-6-tabs-data-is-replaced-by-last-tab – karthik kolanji Feb 25 '19 at 14:36

1 Answers1

4

Take a look at ViewModelProvider.get(@NonNull String key, @NonNull Class<T> modelClass), you should be able to have multiple ViewModels for a specific class stored by key.

ViewModelProvider.get(@NonNull Class<T> modelClass) just calls that first method with a default key.

The get call interacts with ViewModelStore which is a wrapper around a HashMap<String, ViewModel>, which should allow you to store various ViewModels for the same type of Fragment, as long as each has a key that's unique to identifying what it should display.

Bryan Dormaier
  • 800
  • 6
  • 10