Share Viewmodels Between Fragments Or Share Livedata Between Viewmodels
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 i
Solution 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.
Post a Comment for "Share Viewmodels Between Fragments Or Share Livedata Between Viewmodels"