问题
Basically I want a way to properly share ViewModels between fragments OR share LiveData between ViewModels.
My scenario:
I have 2 fragments (FragmentA
& FragmentB
) - each has its own ViewModels:
FragmentA
has ViewModelA
, FragmentB
has ViewModelB
.
ViewModelA
has LiveDataA1
, ViewModelB
has LiveDataB1
and LiveDataB2
ViewModelB
is only allowed to have LiveDataB2
and ViewModelA
cannot have it.
Problem is I want FragmentA
to observe LiveDataB2
from ViewModelB
.
Approach#1:
Aside from ViewModelA
, ViewModelB
is also be used in FragmentA
(so it's like 2 ViewModels in FragmentA).
So FragmentA
will observe LiveDataB2
from ViewModelB
.
This is my current implementation now. But I feel like it's not proper to have another ViewModel that is intended for other fragments. I thinking that each Fragment should only have 1 ViewModel.
Approach#2:
Create a new SharedViewModel
.
So we will have 3 ViewModels now:
ViewModelA
has LiveDataA1
, ViewModelB
has LiveDataB1
, SharedViewModel
has LiveDataB2
.
(Here I move LiveDataB2
from ViewModelB
to SharedViewModel
)
Aside from ViewModelA
, SharedViewModel
is also be used in FragmentA
.
So FragmentA will observe LiveDataB2
from SharedViewModel
.
So I guess its the same as #1 but I guess but here I'm thinking that SharedViewModel
is just a util ViewModel to just like get the shared data needed.
So here we are like putting all the LiveDatas that can be common/shared between FragmentA and FragmentB (or even with other fragments)
Approach#3:
Share LiveData between ViewModels.
I think this is wild and I don't know how to implement this.
But I'm thinking that there will a new LiveDataA2
in ViewModelA
that refers to the same instance as LiveDataB2
in ViewModelB
.
So FragmentA
will only have ViewModelA
and can observe LiveDataA2
.
If there is a change in LiveDataB2
in ViewModelB
, FragmentA
will have it.
Badly need some advise here on which the proper way!
回答1:
Shared ViewModel is the right approach
You should use a single Shared ViewModel
for both fragments FragmentA
and FragmentB
with multiple live data objects LiveDataA1
, LiveDataB1
and LiveDataB2
, with this approach your FragmentA
can easily observe LiveDataB2
.
Now, the problem with your approaches are:
Approach#1:
If FragmentA
creates an instance of ViewModelB
you will not get ViewModelB
associate with FragmentB
so ViewModelB
lost its state.
Approach#2:
Somehow the problem is you are creating separate ViewModel
when there is a recommended way i.e Shared ViewModel
as per official docs
Approach#3:
Sharing LiveData
objects is not the right approach as it is associated with lifecycle owner.
来源:https://stackoverflow.com/questions/60796010/share-viewmodels-between-fragments-or-share-livedata-between-viewmodels