简体   繁体   中英

What is the difference between passing“this” and “activity!!” as a ViewModelStoreOwner while creating ViewModelProvider instance

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 (a Fragment ) or activity!! (a FragmentActivity ) to the ViewModelProvider constructor because both implement the ViewModelStoreOwner interface.

The role of a ViewModelStoreOwner is to be able to provide a ViewModelStore , when needed, where the ViewModelStore represents a collection of existing viewmodels:

  • If you use this and pass a Fragment to the ViewModelProvider constructor, the ViewModelStore will be tied to that Fragment . 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 a FragmentActivity to the ViewModelProvider constructor, the ViewModelStore will be tied to that FragmentActivity . 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 .

"this" means "Context", which is the Fragment you are Instantiated the viewModel.

From the code you provided i can understand "this" = "InventoryDetailsFragment", which is >the class you instantiated the viewModel.

Your code should look like this

val application = requireNotNull(activity).application
viewModelFactory = InventoryDetailsFragmentViewModelFactory(application)
viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(InventoryDetailsFragmentViewModel::class.java)

If you want to see an example where ViewModel and ViewModelFactory are used in a project visit this link sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM