[英]Where to Save ViewModel State in Android's MVVM?
As a beginner to Android development, I am trying to clean up my codebase from my first app by converting it to the recommended MVVM structure.作为 Android 开发的初学者,我正在尝试通过将我的第一个应用程序转换为推荐的 MVVM 结构来清理我的代码库。 What I am currently stuck on, is trying to figure out the best way to store my view model's state.
我目前坚持的是试图找出存储我的视图模型 state 的最佳方法。
In this example, the state I need to store is simply an ArrayList of strings (indicating which checkboxes in a recyclerview are checked).在这个例子中,我需要存储的 state 只是一个 ArrayList 字符串(表示选中了回收视图中的哪些复选框)。 I am currently storing this ArrayList inside of my ViewModel as a field, wrapped inside of a MutableLivedata object, which my activity observes.
我目前将这个 ArrayList 作为一个字段存储在我的 ViewModel 中,包裹在我的活动观察到的 MutableLivedata object 中。 This method of storing the ViewModel state as a field does not seem viable in the long run.
从长远来看,这种将 ViewModel state 存储为字段的方法似乎不可行。 I can imagine as my app grows my ViewModel classes would get quite bloated and messy.
我可以想象随着我的应用程序的增长,我的 ViewModel 类会变得非常臃肿和混乱。
I currently use a Firebase Realtime Database to store my data that I need persisted, accessed through a repository just as Android Architecture recommends.我目前使用 Firebase 实时数据库来存储我需要持久化的数据,就像 Android 架构建议的那样,通过存储库访问。 My ViewModel's state, however, does not need to be persisted after the app closes, so it would definitely not make sense to make network calls to my Firebase Database for it.
然而,我的 ViewModel 的 state 不需要在应用程序关闭后持久化,因此对我的 Firebase 数据库进行网络调用绝对没有意义。
My question is: Where would make the most sense to save my ViewModel's state?我的问题是:在哪里保存 ViewModel 的 state 最有意义? The semi-sensible options I see in front of me are saving it as fields in my ViewModel class (my current approach), saving it in a Room database (and resetting the database each time the app is killed), or saving it as fields in my repository class (doesn't seem right).
我在我面前看到的半明智选项是将其保存为 ViewModel class 中的字段(我当前的方法),将其保存在 Room 数据库中(并在每次应用程序被终止时重置数据库),或将其保存为字段在我的存储库 class 中(似乎不对)。 I'm open to suggestions!
我愿意接受建议!
It depends on your needs:这取决于您的需求:
In any case storing data remotely does not seem to be the the solution that you are looking for.在任何情况下,远程存储数据似乎都不是您正在寻找的解决方案。
I would also not rely on memory cache solution because of Android system memory reclaim situations.我也不会依赖 memory 缓存解决方案,因为 Android 系统 memory 回收情况。
You can go with the cache solution and clear your cache when you open the app again.您可以使用缓存解决方案 go 并在再次打开应用程序时清除缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.