Android Hilt - Shared ViewModel between two Fragments - android

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

Related

Sharing ViewModel in ViewPager using parent fragment as owner

I have a parent Fragment A with Fragment B and Fragment C inside a ViewPager. I want to share Fragment's A ViewModel within Fragment B and Fragment C.
This was my approach which seemed intuitive at first:
In parent Fragment A which contains ViewPager, I create my viewModel like this:
val viewModel by viewModels<SharedViewModel>()
...
#HiltViewModel
class SharedViewModel #Inject constructor(
stateHandle: SavedStateHandle
) {
val myArgument = stateHandle.get<Boolean>("myArgument")
...
}
My ViewPager Fragment's B and C are trying to access same SharedViewModel instance like this:
private val sharedViewModel by viewModels<SharedViewModel>(
ownerProducer = { requireParentFragment() }
)
Everything works fine, except when the process is destroyed, my savedStateHandle in the SharedViewModel does not retain arguments passed by navigation component. Doing this in SharedViewModel returns null and savedStateHandle is empty.
val myArgument = stateHandle.get<Boolean>("myArgument")
Does someone know why is this happening? Using activityViewModels seems to fix this, but I do not fully understand why.

Hilt Create one view model instance shared between the activity and their fragments

Iam trying to create shared view model between activity and the fragments.
In the activity :
val viewModel: SharedViewModel by viewModels()
And in fragments:
val viewModel: SharedViewModel by navGraphViewModels(R.id.activity_nav_graph) {
defaultViewModelProviderFactory
}
But 2 instances currently created one on the activity and one in the fragments
in your fragment should be
private val viewModel: SharedViewModel by activityViewModels()

Using same viewmodel on different fragments

I have viewModel on Fragment A, which I load in this way:
viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)
then from fragment A, I go to fragment B. Is this possible to use the same viewmodel on fragment B? In Fragment B I tried (as in docs):
private val viewModel: AFragmentVM by activityViewModels()
but I get an exception while trying to use this ViewModel:
java.lang.RuntimeException: Cannot create an instance of class ...AFragmentVM
...
BFragment.getViewModel(Unknown Source:2)
BFragment.onCreateView(ChartFragment.kt:40)
...
Caused by: java.lang.NoSuchMethodException: ...AFragmentVM.<init> [class android.app.Application]
EDIT:
Based on #SebastienRieu and #IntelliJ Amiya answers, everything that I had to do was to create ViewModel on Fragment A in this way:
viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)
Or:
viewModel = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)
Then on Fragment B I could use:
private val viewModel: AFragmentVM by activityViewModels()
If the two fragments are in the same activity you should replace this :
viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)
by this
viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)
and add a viewModel in the activity and initialize it in this activity like this :
viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)
With requireActivity() when setup the VM in fragment you tell the fragment to use the activity shared ViewModel
Fragment A
viewModel = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)
Fragment B
private lateinit var viewModel: AFragmentVM

How to use same instance of ViewModel in activity as well as fragment?

I have created an instance of ViewModel in MainActivity and setup an observer. I want the observed data into one of the fragments of MainActivity's ViewPager. How can I get the required LiveData into the fragment.
Using AndroidX extension delegate
In the MainActivity:
private val activityViewModel: SomeViewModel by viewModels()
In the Fragement
private val activityViewModel: SomeViewModel by activityViewModels()
With ViewModelFactory, put the ViewModelFactory intance into closure
private val activityViewModel: SomeViewModel by viewModels{ viewModelFactory }
private val activityViewModel: SomeViewModel by activityViewModels{ viewModelFactory}
you can use shared ViewModel
Shared ViewModel between activity and fragments
for this you can define an object from activity's viewModel in your fragment with activity as viewModel's owner and apply changes on that's variables.

Access `ViewModel` inside `Activity` scoped to navigation graph

Inside Activity you can get a ViewModel scoped to that Activity like this:
val viewModel = ViewModelProviders.of(this)[ViewModel::class.java] //deprecated way
val viewModel = ViewModelProvider(this)[ViewModel::class.java]
//or
val viewModel by viewModels<ViewModel>()
Similarly in a Fragment you can get a ViewModel by
//scoped to parent Activity
val viewModel: ViewModel by activityViewModels()
//scoped to parent Fragment
val viewModel: ViewModel by viewModels({ requireParentFragment() })
//scoped to navigation graph
val viewModel: ViewModel by navGraphViewModels(R.id.login_graph)
Now if I try to access a ViewModel inside Activity which is scoped to a navigation graph then there is no helper method so I have to do
val viewModel by lazy {
ViewModelProvider(findNavController(R.id.nav_host_fragment)
.getViewModelStoreOwner(R.id.your_graph).viewModelStore,
ViewModelProvider.AndroidViewModelFactory.getInstance(application)
).get(ViewModel::class.java)
}
Is there a helper method that I have missed? Do I have to access it via navigation graph scope? Can I just use Activity scope to access the same ViewModel?

Categories

Resources