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 to
val viewModel by lazy {
ViewModelProvider(this, ViewModelFactory(this,Reposityory(),intent)).get(MyViewModel::class.java)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…