Home > Blockchain >  how can i access a shared view model from an activity?
how can i access a shared view model from an activity?

Time:09-17

I have an activity that has many fragments in it, and I want to share things using a shared view model between fragments, but when I initialize it the way I do in fragments it doesn't work, it shows an error, what is the correct way to access it if it is possible?

    val model : sharedViewModel by activityViewModels()

i have tried to do ViewModelProvider but didn't know how to do it properly cause I am coding using kotlin

CodePudding user response:

To have multiple fragments in a common activity instance share a viewmodel, the fragments can use by activityViewModels() property delegate. This returns a viewmodel scoped to the activity.

If you also want the activity to work with this viewmodel, the activity would declare it using the simpler by viewModels() property delegate. They did not bother creating activityViewModels() for an activity, as it would just be the same as the simpler viewModels().

CodePudding user response:

I suggest you read Share data between fragments documentation

Activity use viewModels<T>()

Fragments use activityViewModels<T>()

  • Related