Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 749
PhongBM Avatar asked Oct 19 '25 18:10

PhongBM


1 Answers

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

like image 190
Dương Minh Avatar answered Oct 21 '25 08:10

Dương Minh