Android DataStore 使用详解
创始人
2025-05-28 05:29:42
0

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/127358235
本文出自【赵彦军的博客】

文章目录

  • 概述
  • 使用
  • DataStore 本地数据
  • 查看DataStore 文件
  • Key 的枚举
  • 同步API
  • 清除内容
  • 包含key
  • SharedPreferences 数据迁移
  • DataStore 源码

概述

官方文档:https://developer.android.com/topic/libraries/architecture/datastore

Jetpack DataStore 是一种数据存储解决方案,允许您使用协议缓冲区存储键值对或类型化对象。DataStore 使用 Kotlin 协程和 Flow 以异步、一致的事务方式存储数据。

使用

添加依赖:

implementation "androidx.datastore:datastore-preferences:1.0.0"

定义dataStore

//定义DataStore
val Context.dataStore: DataStore by preferencesDataStore(name = "user_info")//定义key 
val keyName = stringPreferencesKey("name")
val keyAge = intPreferencesKey("age")

保存数据:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.preferences.core.edit
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launchclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)lifecycleScope.launch {saveData("zhaoyanjun", 18)}}//dataStore保存数据suspend fun saveData(name: String, age: Int) {dataStore.edit {it[keyName] = name //保存字符串it[keyAge] = age //保存int}}}

获取数据

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)lifecycleScope.launch {getData()}}//dataStore获取数据,collect 是一个挂起函数,所以会一直挂起,只要name的值发起变更,collect 就会回调suspend fun getData() {val nameFlow = dataStore.data.map {it[keyName]}nameFlow.collect { name ->Log.d("getData ", "name $name")}}
}

dataStore.data 是一个 Flow 对象,使用一个 collect 操作符 可以接受 值的变化,一旦值发生变化,collect { } 就会回调,可以实现数据驱动 UI 的效果。

DataStore 本地数据

DataStore 文件在 files/datastore/ 目录,完整路径是

/data/data/com.zyj.exoplayerdemo/files/datastore/user_info.preferences_pb

在这里插入图片描述

查看DataStore 文件

双击 user_info.preferences_pb 在 AS 里打开

在这里插入图片描述

发现是乱码。

点击右键把 user_info.preferences_pb 导出到桌面

在这里插入图片描述
在 mac appStore 下载安装 Protobuf Viewer

在这里插入图片描述

Protobuf Viewer 打开我们导出的 pb 文件

在这里插入图片描述

Key 的枚举

在文中我们用到了

stringPreferencesKey("name")
intPreferencesKey("age")

除此之外,DataStore 还提供了其他类型的 Key

@JvmName("intKey")
public fun intPreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("doubleKey")
public fun doublePreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("stringKey")
public fun stringPreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("booleanKey")
public fun booleanPreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("floatKey")
public fun floatPreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("longKey")
public fun longPreferencesKey(name: String): Preferences.Key = Preferences.Key(name)@JvmName("stringSetKey")
public fun stringSetPreferencesKey(name: String): Preferences.Key> =Preferences.Key(name)

同步API

在上面的演示过程中,我们使用 Flowcollect { } 操作符 , 但是 collect { } 会一直处于挂起状态,只要值发生变化,我们就会收到通知,符合数据驱动 UI 的设计模式。

但是在现实开发中,我们往往需要一个同步 api , 仅仅获取当前一次值,我们只关注本次的值是什么,至于以后得值变化,我们不关心。DataStore 提供了 同步api 来供我们使用 。

override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)lifecycleScope.launch {//同步apival first = dataStore.data.first()val name = first[keyName]val age = first[keyAge]Log.d("getData ", "name $name")Log.d("getData ", "age $age")}}

如果是 pb 文件里面没有值,那么就会返回 null

com.zyj.exoplayerdemo D/getData: name null
com.zyj.exoplayerdemo D/getData: age null

所以我们可以把获取名字,封装成一个同步方法

suspend fun getNameData(): String? {val nameFlow = dataStore.data.map {it[keyName]}return nameFlow.first()
}

清除内容

清除某个key

val keyName = stringPreferencesKey("name")suspend fun clear() {dataStore.edit {it.remove(keyName)}
}

清除所有值

   suspend fun clear() {dataStore.edit {it.clear()}}

包含key

suspend fun contains() {dataStore.edit {//是否包含某个keyvar result =  it.contains(keyName)}
}

SharedPreferences 数据迁移

如果你原来是用 SharedPreferences , 想换到 DataStore 上,DataStore 提供了一键迁移,就一行代码就搞定了。

val Context.dataStore: DataStore by preferencesDataStore(name = "user_info",produceMigrations = { context ->listOf(SharedPreferencesMigration(context, "sp_file_name"))})

DataStore 源码

DataStore 是一个接口

public interface DataStore {/*** Provides efficient, cached (when possible) access to the latest durably persisted state.* The flow will always either emit a value or throw an exception encountered when attempting* to read from disk. If an exception is encountered, collecting again will attempt to read the* data again.** Do not layer a cache on top of this API: it will be be impossible to guarantee consistency.* Instead, use data.first() to access a single snapshot.** @return a flow representing the current state of the data* @throws IOException when an exception is encountered when reading data*/public val data: Flow/*** Updates the data transactionally in an atomic read-modify-write operation. All operations* are serialized, and the transform itself is a coroutine so it can perform heavy work* such as RPCs.** The coroutine completes when the data has been persisted durably to disk (after which* [data] will reflect the update). If the transform or write to disk fails, the* transaction is aborted and an exception is thrown.** @return the snapshot returned by the transform* @throws IOException when an exception is encountered when writing data to disk* @throws Exception when thrown by the transform function*/public suspend fun updateData(transform: suspend (t: T) -> T): T
}

相关内容

热门资讯

王毅:日本现职领导人讲了不该讲... 据外交部网站,11月19日至22日,中共中央政治局委员、外交部长王毅应邀赴吉尔吉斯斯坦、乌兹别克斯坦...
陕西兴平失联的12岁双胞胎姐妹... 据大风新闻,11月21日晚7时17分,陕西兴平一对12岁的双胞胎姐妹从家里外出。走的时候还穿着蓝色校...
原创 中... 中国再下一令,日本却辗转从韩国口中才得知这个噩耗,高市有点坐不住了,关键时刻放出猛料,要把美国拉下水...
公园掰手腕致骨折起诉索赔被驳回 公园内一场普通的掰手腕,竟导致手臂骨折、花费数万元医疗费。近日,江苏省苏州工业园区人民法院审理了一起...
护航浙商出海发展 浙江省涉外法... 中新网杭州11月23日电 (钱晨菲 吴怡欣)11月23日,浙江省涉外法律服务合作对接会在杭州举行,浙...
吕文君社媒庆祝夺冠:不只是海港... 2025赛季中超联赛于昨日正式落幕,上海海港队凭借出色的表现,成功捧起了冠军奖杯,成为了中超历史上又...
日本政府顾问:无需等到160关... 日本政府顾问表示,高市早苗政府对日元干预将采取更积极姿态,以抑制日元疲软带来的通胀压力,干预门槛可能...
被摄影师起诉侵权 视觉中国公开... 来源:每日经济新闻 持续两年多的摄影师起诉视觉中国(000681.SZ)侵权一案近日迎来进展。 法...
《哪吒2》被质疑过多使用动捕技... 搜狐娱乐讯 22日,奥斯卡公开的最佳动画长片奖“符合参评资格”大名单中没有《哪吒之魔童闹海》,引发热...
为了少付合同款,湖南一公司诉讼... 华声在线11月23日讯(文/视频 全媒体记者 杨昱 通讯员 胡云淞)为了少支付40万元合同款及利息,...