12

I'm new to Android Architecture Components and I have read this tutorial. I'm interested in the part where it said:

This allows you to have an app that opens a lot of different instances of the same Activity or Fragment, but with different ViewModel information. Let’s imagine if we extended our Court-Counter example to have the scores for multiple basketball games. The games are presented in a list, and then clicking on a game in the list opens a screen that looks like our current MainActivity, but which I’ll call GameScoreActivity.

Let's say I have a ViewModel MyViewModel. And I want to create a list of this view model but I don't know the number of elements in this list until runtime. Is it convenient to create the view model instances inside a for loop? How many instances am I allowed to create? Will the number of instances affect performance?

Motassem Jalal
  • 1,254
  • 1
  • 22
  • 46
  • why would you want to create such a list? make a list inside your `MyViewModel` instead – pskink Jan 30 '18 at 10:55
  • @pskink because when I click on on of the item I need to display extra information for that Item. Take the example mentioned in the tutorial, why did the writer mentioned multiple model views? – Motassem Jalal Jan 30 '18 at 11:46

2 Answers2

6

ViewModel providers take an optional key which you can use to distinguish ViewModel instances.

miguel
  • 16,205
  • 4
  • 53
  • 64
1

There is an 1 to 1 relation between Activity instance and ViewModel instance. You can have a few instances of the same Activity and each of them is supposed to have it's own unique ViewModel instance. There is no point in having many instances of the same ViewModel class inside the single Activity instance.

Igor Bubelov
  • 5,154
  • 5
  • 25
  • 24
  • 10
    Budelov, is there a way to have different instances of the same viewmodel class for different instances of the same fragment, attached to one activity? i am replacing a fragment with another instance of the same fragment class, but viewmodel instance remains. i would like to have another instance of viewmodel as well – Євген Гарастович May 03 '18 at 12:47
  • @ЄвгенГарастович: Got any solutions?. I too need this . https://stackoverflow.com/q/54862222/4432176 – karthik kolanji Feb 25 '19 at 09:38
  • nothing so far. but you can try creating your own ViewModelFactory. perhaps it will help – Євген Гарастович Mar 06 '19 at 17:29
  • Igor can you please answer my question about that part on viewModel also using Paging https://stackoverflow.com/q/63725734/11567530 – Ahmed Elsayed Sep 06 '20 at 09:05
  • 2
    @ЄвгенГарастович, you should just create your VM using `viewModels()` delegate (instead of `activityViewModels`): `private val myViewModel: MyViewModel by viewModels()`. This will scope your VM to the fragment instance, so, different fragment instances will have different VM instances. – James Bond Dec 29 '21 at 11:12