I would like to ask if it's correct to share the same ViewModel
between Fragment
and its Activity
.I have UserDetailActivity
and UserDetailFragment
. Can I use the same ViewModel
to display detail data of a user in the UserDetailActivity
and UserDetailFragment
or is there better approach.
Sharing data between fragment and its parent activity using ViewModel
735 views Asked by Martin At
2
There are 2 answers
0
On
I am not using MVVM but I think its the same with MVP, I use the same Presenter(ViewModel in your case) with my Activity and its child Fragment. It make since because a Fragment is literally a fragment of an Activity. There might be some special cases where you really want to separate viewModel of Fragment and Activity, but most of the time, they share. About the initialization, dont pass your viewmodel directly, you can use dagger and inject it.
Yes you can pass ViewModal object from a Activity to Fragment or vice-versa by implementing Parcelable into ViewModal class and can share object with fragment setArguments() method.