Reputation: 49
I'm using viewModel in my project already. But ı know ı can initalize viewmodel with many ways. Do you know what are the differences between these ways?
What are the technical differences?
Upvotes: 1
Views: 179
Reputation: 1596
By using
viewModel = ViewModelProvider(this).get(ViewModelClass::class.java)
your are creating an instance of ViewModelClass
scoped to this Fragment/activity and whenever the activity gets recreated same instance of the viewmodel is assigned rather than a new instance
viewModel = ViewModelClass()
though it seems to be correct, it isn't . Whenever the activity gets recreated, new instance of viewmodel is assigned. Dont try to create an instance of ViewModel by directly calling its constructor, instead let the ViewModelProvider
do the job.
viewModel: ViewModelClass by viewModels()
courtesy of Android KTX here you delegate the creation of ViewModel . Its similar to
val viewModel by lazy{
ViewModelProvider(this).get(MyViewModel::class.java)
}
viewModel : ViewModelClass by ViewModels{ ViewModelFactory(this,Reposityory(),intent)}
its similar toval viewModel by lazy {
ViewModelProvider(this, ViewModelFactory(this,Reposityory(),intent)).get(MyViewModel::class.java)
}
Upvotes: 2