Reputation: 1392
I have know that an Activity/Fragment has to create a ViewModel, and the ViewModel can be created from a ViewModelFactory. And the ViewModel itself are using a data repository which handles the data from either database or network. And the ViewModel is not a singleton.
For example, I have an activity which has two fragment, fragment A and fragment B, and I'm only able to access them one by one. In the fragment A, I load some data from a repository which came from a network or database. When I navigate to fragment B, the data in a fragment A is lost, so I have to load it back from a network or database which takes time. Because of that I would like to store my data somewhere in the runtime.
My question, what is the best approach to solve this problem? Is it okay to create a singleton in the repository?
Upvotes: 0
Views: 199
Reputation: 1389
you need to use a shared viewModel, a ViewModel that is shared between your fragments and survives navigating between certain fragments.
Implementation depends on what you use in your project. you can create a ViewModel in the activity and access them from your fragments and put the shared data in this ViewModel. or if you are using navigation component you can have a shared ViewModel per nav graph. and with dagger and koin you can define a costume scope for your ViewModel to survive. see these links:
Share data between fragments
Share data between fragments with shared viewModel
Upvotes: 1