原文地址: Jetpack架构学习(7)——使用DataStore存储配置信息-Stars-One的杂货小窝
这里由于开发的app使用的compose架构,比较适合与DataStore一起使用,所以稍微学习了使用方法,顺便记录下
其实DataStore
和SharePreference
使用方式类似,就是如果你的是新项目,没有啥历史包袱,可以试着用下,使用Flow和Compose使用还是挺舒服的
介绍
DataStore分2种类型:
Preferences DataStore
存储配置信息Proto DataStore
存储对象数据(二进制)
常用的存储配置信息,存储对象数据一般比较少用,这里也不深究了
使用
1.依赖导入
// Preferences DataStore (SharedPreferences like APIs)
dependencies {
implementation("androidx.datastore:datastore-preferences:1.1.7")
}
// Alternatively - use the following artifact without an Android dependency.
dependencies {
implementation("androidx.datastore:datastore-preferences-core:1.1.7")
}
2.数据读取和写入
这里,首先得给Context加个扩展方法,用来创建我们的DataStore实例
//需要在顶层kt文件创建,name参数可以任取
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
一般我们一个app,只需要用到一个DataStore即可,如果你想要创建多个,可以搞几个扩展方法,然后创建不同名字的DataStore
下面给一个简单封装示例,用于存储keyexample_counter的为int类型数据:
class MySetting(val context:Context){
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
//写入数据:
suspend fun incrementCounter(data:Int) {
context.dataStore.edit { settings ->
settings[EXAMPLE_COUNTER] = data
}
}
//读取数据
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[EXAMPLE_COUNTER] ?: 0
}
}
intPreferencesKey
用来定义你的数据key,从名字看得出来,你的key对应的数据是int类型,除此之外,还有其他几个方法:doublePreferencesKey
stringPreferencesKey
booleanPreferencesKey
floatPreferencesKey
longPreferencesKey
stringSetPreferencesKey
byteArrayPreferencesKey
从名字可以直接看得出类型,这里就不解释了
如果你还是想使用同步方法调用,可以使用协程的runBlocking
方法
页面使用:
val context = LocalContext.current
val mySetting remember { MySetting(context)}
Column(){
val num by mySetting.exampleCounterFlow.collectAsState(0)
Text(num.toString())
}
参考
- App Architecture: Data Layer – DataStore – Android Developers | App architecture
来源链接:https://www.cnblogs.com/stars-one/p/19019101
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容