原文地址: 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
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |