How to share same viewModel between dialog and dialogFragment? I know that viewModel can be shared in activity scope. But it is too big scope for me.
private val model: SharedViewModel by activityViewModels()
Unfortunately I don't have in a project navigation component.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
You can't share a ViewModel across Activities. That's specifically one of the downsides of using multiple activities as per the Single Activity talk.
Use activity's scope to create an instance of the ViewModel in fragment so that all the fragments and activity now has a common ViewModel and have access to the same ViewModelStore. If the activity is re-created, it and all its fragments receive the same ViewModel instance that was created by the associated activity.
Data sharing between Fragments. Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity. Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.
We have created the object of SharedViewModel which is the same object as we are using the same single activity as an owner. This is the reason it is shared. Notice that we have used the requireActivity () in both the fragments.
Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity. Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.
Use childFragmentManager
to show DialogFragment
Declare shared ViewModel
inside Fragment
by
private val sharedViewModel: YourViewModel by viewModels()
DialogFragment
declare ViewModel
byprivate val sharedViewModel: YourViewModel by viewModels(ownerProducer = { requireParentFragment() })
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