Yakin Wissem
Yakin Wissem

Reputation: 57

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

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

Upvotes: 4

Views: 3491

Answers (2)

Emmanuel Mtali
Emmanuel Mtali

Reputation: 4973

I suggest you read Share data between fragments documentation

Activity use viewModels<T>()

Fragments use activityViewModels<T>()

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006944

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().

Upvotes: 5

Related Questions