Recently, I stumbled across the concept of shared ViewModels, which intrigued me since I seem to be writing the same ViewModels for my fragments.
For instance I have a series of Fragments with RecyclerViews which navigate:
Main List -> Sub List -> Item List -> Item Details.
Each Fragment has its own ViewModel, however the lists are being populated from the same repository which is pulling from the same database. The only operations being performed are various get commands, the user doesn't make any modifications to the database.
In this case does it make sense to put all my repository queries in one list ViewModel?
From the google doc it sounds like this is more intended for sharing data in situations when there are multiple fragments on screen. I can see how I could use this to send the selected item from one fragment to the next, but I'm already achieving that quite nicely with Navigation safeArgs.
Probably it depends on what kind of situation you have. For example, keep the state in a shared view model would be nice if your app has a complex state and always push from fragment to fragment via the safeArgs is not good, because it takes time to serialize/deserialize, and also you must control where is an actual state. However, with one common shared across multiply fragment view model could work as a single source of truth for your state.
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