Injecting ViewModel into ViewModel with Hilt
Asked Answered
O

1

10

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?

Oloroso answered 13/1, 2021 at 14:53 Comment(1)
Can you share a bit of code showing how to do this with hilt?Bucktooth
C
0

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

Carmine answered 13/1, 2021 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.