I'm currently working on a big project where I have a ViewModelA using MediatorLiveData to observe other LiveData sources. I would like to have this ViewModelA observing data from a ViewModelB.
One way to solve this would be having the Fragment using both view models and updating ViewModelA when ViewModelB data changes.
@AndroidEntryPoint
class FragmentA: Fragment() {
//ViewModels
private val viewModelA: ViewModelA by viewModels()
private val viewModelB: ViewModelB by viewModels()
onViewCreated... {
viewModelA.someFunction().observe{
viewModelB.someLiveData.value = it
}
}
}
However I came up with another solution where I inject ViewModelB into ViewModelA's constructor using Hilt.
class ViewModelA @ViewModelInject constructor(
private val viewModelB: ViewModelB
) : ViewModel() {}
It currently works but I don't think this would be a good practice. I couldn't find much info online on this matter. Would that cause any problems?
You can achieve the same if you forward the result from ViewModelA
to ViewModelB
. This will give you the benefit of separation, viewmodels wont be intertwined and improved testability. ViewModelA
should not be aware who is consuming the result.
viewModela.myLiveData.observe(viewLifecycleOwner, viewModelB::onDataRetrieved)
In onDataRetrieved
you will have your own logic for calling viewModelB.someLiveData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With