Search code examples
javaandroidkotlinandroid-lifecycle

Accessing ViewModel in ParentFragment from ChildFragment using viewModels


I am trying to access the ParentViewModel for ParentFragment from ChildFragment using viewModels. This is my code.


// In ParentFragment

class ParentFragment : Fragment() {
    val parentViewModel: ParentViewModel by viewModels {
        ParentViewModelFactory(getRepository())
    }
    ...
}

// In ChildFragment

class ChildFragment : Fragment() {
    val parentViewModel: ParentViewModel by viewModels(
        { requireParentFragment() }
    )
    ...
}

However, this code only works when I setup a LiveData variable in ParentViewModel and have ParentFragment observe it like so:

parentViewModel.text.observe(this) {
    toast(it)
}

I have no use for observing the ViewModel from inside ParentFragment. I only need it to define the lifecycle for the ChildFragments.

If I get rid of the observation above I get this error:

'java.lang.RuntimeException: Cannot create an instance of class ParentViewModel'
How can I have the ChildFragments access the ParentViewModel without setting up dummy live data objects so as the ParentFragment can observe them.


Solution

  • In ChildFragment you should pass factory when init it. Try this

    class ChildFragment : Fragment() {
        val parentViewModel: ParentViewModel by viewModels(
            { requireParentFragment() }
        ) { ParentViewModelFactory(getRepository()) }
        ...
    }