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?