I'm using Jetpack Navigation and Hilt in my project and I want to share ViewModel between only two Fragments, like this:
How to config ViewModel B like that?
UPDATE: I found a way to use Hilt Custom Scope, but I don't know how to implement it yet.
Thanks in advance.
You can use activityViewModels()
with the ViewModel following the host activity's lifecycle.
class BFragment: Fragment() {
// Using the activityViewModels() Kotlin property delegate from the
// fragment-ktx artifact to retrieve the ViewModel in the activity scope
private val viewModel: BViewModel by activityViewModels()
}
class CFragment : Fragment() {
private val viewModel: CViewModel by viewModels()
private val shareViewModel: BViewModel by activityViewModels()
}
Or if fragment C is a child fragment of B, you can customize the viewmodel's lifecycle as follows:
class BFragment: Fragment() {
// Using the viewModels() Kotlin property delegate from the fragment-ktx
// artifact to retrieve the ViewModel
private val viewModel: BViewModel by viewModels()
}
class CFragment: Fragment() {
// Using the viewModels() Kotlin property delegate from the fragment-ktx
// artifact to retrieve the ViewModel using the parent fragment's scope
private val shareViewModel: BViewModel by viewModels({requireParentFragment()})
private val viewModel: CViewModel by viewModels()
}
More information: Communicating with fragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With