Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting ViewModel into ViewModel with Hilt

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?

like image 500
hbarn Avatar asked Nov 07 '22 03:11

hbarn


1 Answers

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

like image 142
Nikola Despotoski Avatar answered Nov 14 '22 22:11

Nikola Despotoski