Issue
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
Solution
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()
.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.