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
You can use navGraphViewModels
. Create a nested graph with Fragment B & C, both will share the same navGraphViewModel
<navigation android:id="@+id/nav_graph_a"
app:startDestination="@id/dest_a">
<fragment android:id="@+id/dest_a"/>
<navigation android:id="@+id/nav_graph_b_c"
app:startDestination="@id/dest_b">
<fragment android:id="@+id/dest_b"/>
<fragment android:id="@+id/dest_c"/>
</navigation>
</navigation>
https://developer.android.com/guide/navigation/navigation-programmatic
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.