Hi I am a Kotlin learner, wanted to understand the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance in a fragment for ex
viewModel = ViewModelProvider(
this,
InventoryDetailsFragmentViewModelFactory.getInstance(activity!!.application)
)
.get(InventoryDetailsFragmentViewModel::class.java)
when I am using this as owner sometimes observer is not working Please help me to understand difference in using this and activity!!
You are able to pass either
this(aFragment) oractivity!!(aFragmentActivity) to theViewModelProviderconstructor because both implement theViewModelStoreOwnerinterface.The role of a
ViewModelStoreOwneris to be able to provide aViewModelStore, when needed, where theViewModelStorerepresents a collection of existing viewmodels:If you use
thisand pass aFragmentto theViewModelProviderconstructor, theViewModelStorewill be tied to thatFragment. This fragment and child fragments might share viewmodels, but those viewmodels should not be shared with other peer fragments or parents.If you use
activity!!and pass aFragmentActivityto theViewModelProviderconstructor, theViewModelStorewill be tied to thatFragmentActivity. Not only can this activity use the viewmodel, but any fragments used in that activity could also share that viewmodel.You need to decide what the proper scope is of your
InventoryDetailsFragmentViewModel.