简体   繁体   中英

Android Hilt - Shared ViewModel between two Fragments

I'm using Jetpack Navigation and Hilt in my project and I want to share ViewModel between only two Fragments, like this:

  • Fragment A: use ViewModel A
  • In Fragment A navigate to Fragment B: use ViewModel B
  • In Fragment B navigate to Fragment C: use instance of ViewModel B
  • If from C back to B, back to A then ViewModel B will be destroyed.

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

https://medium.com/sprinthub/a-step-by-step-guide-on-how-to-use-nav-graph-scoped-viewmodels-cf82de4545ed

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM