Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 512
Yakin Wissem Avatar asked Oct 22 '25 18:10

Yakin Wissem


2 Answers

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

like image 107
CommonsWare Avatar answered Oct 25 '25 07:10

CommonsWare


I suggest you read Share data between fragments documentation

Activity use viewModels<T>()

Fragments use activityViewModels<T>()

like image 44
Emmanuel Mtali Avatar answered Oct 25 '25 08:10

Emmanuel Mtali