Search code examples
androidandroid-architecture-componentsandroid-viewmodel

Android Architecture Components: Multiple instances of the same view model


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?


Solution

  • 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.