欢迎使用 Jetpack DataStore,这是一个经过改进的全新数据存储解决方案,旨在替代原有的 SharedPreferences。Jetpack DataStore 基于 Kotlin 协程和 Flow 开发,并提供两种不同的实现: Proto DataStore 和 Preferences DataStore。其中 Proto DataStore,可以存储带有类型的对象 (使用 protocol buffers 实现);Preferences DataStore,可以存储键值对。在 DataStore 中,数据以异步的、一致的、事务性的方式进行存储,克服了 SharedPreferences 的大部分缺点。
protocol buffers
https://developers.google.cn/protocol-buffers
SharedPreferences 和 DataStore 对比
图片
- SharedPreferences 有一个看上去可以在 UI 线程安全调用的同步 API,但是该 API 实际上执行了磁盘 I/O 操作。此外,apply() 方法会在 fsync() 阻塞 UI 线程。在您应用的任何地方,每当 Service 或 Activity 启动或停止时,就会触发等待 fsync() 的调用。由 apply() 安排的 fsync() 调用过程会阻塞 UI 线程,这也常常成为造成 ANR 的源头。
** SharedPreferences 在分析出错时会抛出运行时异常。
ANR
https://developer.android.google.cn/topic/performance/vitals/anr
在两种实现中,除非另外特指,否则 DataStore 会将首选项存储在文件中,并且所有的数据操作都会在 Dispatchers.IO 上执行。
虽然 Preferences DataStore 与 Proto DataStore 都可以存储数据,但它们的实现方法不尽相同:
Preference DataStore,就像 SharedPreferences 一样,不能定义 schema 或保证以正确的类型访问键值。
Proto DataStore 让您可以使用 Protocol buffers 定义 schema。使用 Protobufs 可以保留强类型数据。它们相对于 XML 或其他相似的数据格式要更快、更小、歧义更少。虽然 Proto DataStore 要求您学习一种新的序列化机制,但考虑到 Proto DataStore 所带来的强类型 schema 的优势,我们认为这样的代价是值得的。
Protocol buffers
https://developers.google.cn/protocol-buffers
Room 和 DataStore 对比
如果您有局部更新数据、参照完整性或支持大型、复杂数据集的需