Android:DataStore 优于 SharedPreferences [英] Android: Benefits of DataStore over SharedPreferences

查看:117
本文介绍了Android:DataStore 优于 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

android Jetpack 团队最近发布了 DataStore 库(仍处于 alpha 阶段),作为使用两种实现保存简单数据的一种方式:

The android Jetpack team recently released the DataStore library (still in alpha) as a way of saving simple data using two implementations:

  1. Preference DataStore 具有与 SharedPreferences 类似的功能,用于存储简单的键值对.
  2. Proto DataStore 用于存储自定义数据类型,需要创建架构.

与其使用 DataStore,不如我们将 sharedPreferences 用于简单数据类型,将 Room 用于更复杂的存储.

Rather than use DataStore, why don't we use sharedPreferences for simple datatypes and Room for more complex storage.

在 ANDROID 中使用 DATASTORE 比使用 SHAREDPREFERNCES(对于简单数据)+ ROOM(对于复杂数据)有什么好处.

推荐答案

引用 弗洛丽娜·穆塔内斯库

SharedPreferences 有几个缺点:在 UI 线程上调用似乎是安全的同步 API、没有发出错误信号的机制、缺乏事务性 API 等等.DataStore 是 SharedPreferences 的替代品,解决了大多数这些缺点.DataStore 包含一个使用 Kotlin 协程和 Flow 的完全异步 API,用于处理数据迁移、保证数据一致性并处理数据损坏.

SharedPreferences comes with several drawbacks: a synchronous API that can appear safe to call on the UI thread, no mechanism for signaling errors, lack of transactional API, and more. DataStore is a replacement for SharedPreferences that addresses most of these shortcomings. DataStore includes a fully asynchronous API using Kotlin coroutines and Flow, handles data migration, guarantees data consistency, and handles data corruption.

这篇关于Android:DataStore 优于 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆