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 theViewModelProvider
constructor because both implement theViewModelStoreOwner
interface.The role of a
ViewModelStoreOwner
is to be able to provide aViewModelStore
, when needed, where theViewModelStore
represents a collection of existing viewmodels:If you use
this
and pass aFragment
to theViewModelProvider
constructor, theViewModelStore
will 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 aFragmentActivity
to theViewModelProvider
constructor, theViewModelStore
will 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
.