简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM