I know about SharedViewModel
(by activityviewModel
) how to share data between ViewModels.
But recently I also learned about navGraphViewModels
.
I've tried both methods in my code using Navigation Component
, but there doesn't seem to be much difference.
Both by activityViewModels
and by navGraphViewModels
confirmed that the data of screen B
is maintained even if it is returned to screen B
after moving to screen A
.
What is the difference between these two?
CodePudding user response:
ActivityViewModel:
activityViewModels() is pretty self-explanatory. It is used to scoped to its activity and when its activity get destroy, activityViewModels() will be destroyed as well.
NavGraphViewModels:
navGraphViewModels() is ViewModel that bind to navigation graph and will persist throughout the entire backstack of that navigation graph. This is how we persist our data throughout certain Fragment and dispose these when exit this navigation graph.
CodePudding user response:
activityViewModels()
returns the view Model which is Scoped to Activity .
Thats means all the Child fragments of this Activity
will be sharing the same Instance of ViewModel
when created by activityViewModels()
.
When created by navGraphViewModels()
the ViewModel is Scoped to navigation graph . it also accepts and Id of Subgraph . this is helpful Whne you do not want to Share Viewmodel b/w all the fragments and just b/w a certain module .
In single Activity Architecture You might want a ViewModel
scoped to SignIn/SignUp graph but not for all other screens . in this case you can use navGraphViewModels
with Sub-graph id and Share same instance only b/w the component of that graph.
If you have a single Graph then both will work more of less same because the scope for both will be same.