So I’ve been trying to learn Android and currently studying about MVVM. So I understood that we can create ViewModels
as a bridge for the interaction between the Views
and the Models
. And in Android, we can create a ViewModel
by extending the ViewModel
class as this won’t dispose the ViewModel
on configuration changes.
And seems like the following is an incorrect way of creating a ViewModel
instance as it will create a new instance of the view model on each recomposition:
val myViewModel = MyViewModel()
The other valid ways I got to know about are:
val mainViewModel by viewModels<MainViewModel>()
val mainViewModel = viewModel<MainViewModel>() // to use this, I had to add another dependency
As the first one comes by default in Android, why don’t we just use the first one only? Why do we use the second one by adding another dependency? Aren’t they supposed to do the same thing?
I’m really sorry if I’m not making sense, just started learning about a few days ago.
2
The difference between the viewModels() and viewModel() is with viewModel() you can give it a ViewModelProvider.Factory if you need give your ViewModel parameters in the constructor for creation in Compose.
Something like this
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val myRepository = MyRepository()
MyViewModel(myRepository= myRepository )
}
}
}
Then you would use it like this
val myViewModel = viewModel<MyViewModel>(factory = MyViewModel.Factory)
The first way is typically used in non-compose applications when you dont need a factory