【发布时间】:2021-02-17 16:30:30
【问题描述】:
我是 Android 开发新手,我即将为我的应用实现简单的首选项。看起来 SharedPreferences 是一条死胡同并且有很多缺点,所以我正在研究 DataStore(非 Proto)与 Room。 由于我已经在我的应用程序中大量使用 Room 和 LiveData(是的,我知道 Flow 是新的热点)来处理其他事情,使用 DataStore 也有什么好处吗?我知道 Room 推荐用于大型或复杂的数据,因为我已经查看了以下内容,但我希望经验更丰富的开发人员可以进一步为我提供帮助:
https://android-developers.googleblog.com/2020/09/prefer-storing-data-with-jetpack.html
https://proandroiddev.com/lets-explore-jetpack-datastore-in-android-621f3564b57
https://medium.com/better-programming/jetpack-datastore-improved-data-storage-system-adec129b6e48
谢谢。
【问题讨论】:
-
您为什么要考虑使用关系数据库来满足用户偏好?
-
“SharedPreferences 是一条死胡同并且有很多缺点”的来源?
-
@ianhanniballake 因为我已经有了一个,我可以快速添加一个更简单的表来存储这些东西而不是数据存储库?我不知道这是否是正确的答案,但这是我目前的思路。
-
@squirrel,查看我发布的第一个网址:
* SharedPreferences has a synchronous API that can appear safe to call on the UI thread, but which actually does disk I/O operations. Furthermore, apply() blocks the UI thread on fsync(). Pending fsync() calls are triggered every time any service starts or stops, and every time an activity starts or stops anywhere in your application. The UI thread is blocked on pending fsync() calls scheduled by apply(), often becoming a source of ANRs. ** SharedPreferences throws parsing errors as runtime exceptions. -
@Bink 对
fsync()的一个有趣的观察,但我不确定有什么替代方案。由于该应用程序可能会在onStop()之后立即被杀死,因此您必须确保完成写入。万一数据还没有进入磁盘,ANR 不是比丢失它更可取吗?此外,运行时异常的替代方法是检查异常;不知道这些会更好
标签: android android-room android-preferences datastore