Search code examples
androidkotlinandroid-livedataandroid-viewmodel

Use variable from ViewModel in Activity. Best practices


I have three List on the VM that I want to use in the activity. These Lists won't change on time, will always be the same, so it is not a State. Should I do the following on the activity?

private val gymListViewModel: GymListViewModel by viewModels()
val myList1 = gymListViewModel.list1
val myList2 = gymListViewModel.list2
val myList3 = gymListViewModel.list3

Is that correct? Or what I should do is use LiveData or Flow to be listening on the activity? Or maybe I should create a data class with three val so I just call that object on the activity?

The other thing that I've been thinking is to call the method that populates the lists, something like: val myList1 = gymListViewModel.getList1() But if I'm not wrong, it's supposed that the VM should not have returning methods, they just update the state. I'm asking this in terms of best practices. Thanks


Solution

  • You can directly access the lists from the ViewModel without involving LiveData or Flow if they are static and immutable.

    class GymListViewModel : ViewModel() {
        val list1: List<String> = listOf("Item1", "Item2", "Item3")
        val list2: List<String> = listOf("Item4", "Item5", "Item6")
        val list3: List<String> = listOf("Item7", "Item8", "Item9")
    }
    
    class GymActivity : AppCompatActivity() {
        private val gymListViewModel: GymListViewModel by viewModels()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_gym)
    
            val myList1 = gymListViewModel.list1
            val myList2 = gymListViewModel.list2
            val myList3 = gymListViewModel.list3
    
            // Use the lists as needed
        }
    }