Sharing ViewModel between three fragments

Viewed 872

I have three fragments A, B and C. B and C are child fragments of A. How do I get all three to share the same view model. From this medium article, this is what I should do:


viewModel = activity?.run {
        ViewModelProviders.of(this)[SharedViewModel::class.java]
    } ?: throw Exception("Invalid Activity")       
}

However this one is about sharing a view model among two fragments and an activity so it can not work right in my case.

1 Answers

Have you tried something like this? Inject your view model into your main root fragment A:

class FragmentA : Fragment() {

    val viewModel: SharedViewModel by viewModels()
}

and now you should be able to access this view model from B and C like this:

class FragmentB : Fragment() {

    val viewModel: SharedViewModel by viewModels(
        ownerProducer = { this.requireParentFragment() }
    )
}
Related