找回密码
 立即注册
首页 业界区 业界 Jetpack架构学习(7)——使用DataStore存储配置信息 ...

Jetpack架构学习(7)——使用DataStore存储配置信息

厌外 2025-8-2 22:36:33
原文地址: Jetpack架构学习(7)——使用DataStore存储配置信息-Stars-One的杂货小窝
这里由于开发的app使用的compose架构,比较适合与DataStore一起使用,所以稍微学习了使用方法,顺便记录下
其实DataStore和SharePreference使用方式类似,就是如果你的是新项目,没有啥历史包袱,可以试着用下,使用Flow和Compose使用还是挺舒服的
介绍

DataStore分2种类型:

  • Preferences DataStore 存储配置信息
  • Proto DataStore 存储对象数据(二进制)
常用的存储配置信息,存储对象数据一般比较少用,这里也不深究了
使用

1.依赖导入
  1. // Preferences DataStore (SharedPreferences like APIs)
  2.     dependencies {
  3.         implementation("androidx.datastore:datastore-preferences:1.1.7")
  4.     }
  5.     // Alternatively - use the following artifact without an Android dependency.
  6.     dependencies {
  7.         implementation("androidx.datastore:datastore-preferences-core:1.1.7")
  8.     }
复制代码
2.数据读取和写入

这里,首先得给Context加个扩展方法,用来创建我们的DataStore实例
  1. //需要在顶层kt文件创建,name参数可以任取
  2. val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
复制代码
一般我们一个app,只需要用到一个DataStore即可,如果你想要创建多个,可以搞几个扩展方法,然后创建不同名字的DataStore
下面给一个简单封装示例,用于存储keyexample_counter的为int类型数据:
  1. class MySetting(val context:Context){
  2.         val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
  3.        
  4.         //写入数据:
  5.         suspend fun incrementCounter(data:Int) {
  6.           context.dataStore.edit { settings ->
  7.             settings[EXAMPLE_COUNTER] = data
  8.           }
  9.         }
  10.        
  11.         //读取数据
  12.         val exampleCounterFlow: Flow<Int> = context.dataStore.data
  13.           .map { preferences ->
  14.             // No type safety.
  15.             preferences[EXAMPLE_COUNTER] ?: 0
  16.         }
  17. }
复制代码

  • intPreferencesKey用来定义你的数据key,从名字看得出来,你的key对应的数据是int类型,除此之外,还有其他几个方法:
  • doublePreferencesKey
  • stringPreferencesKey
  • booleanPreferencesKey
  • floatPreferencesKey
  • longPreferencesKey
  • stringSetPreferencesKey
  • byteArrayPreferencesKey
从名字可以直接看得出类型,这里就不解释了
如果你还是想使用同步方法调用,可以使用协程的runBlocking方法
页面使用:
  1. val context = LocalContext.current
  2. val mySetting  remember { MySetting(context)}
  3. Column(){
  4.     val num by mySetting.exampleCounterFlow.collectAsState(0)
  5.     Text(num.toString())
  6. }
复制代码
参考


  • App Architecture: Data Layer - DataStore - Android Developers  |  App architecture

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册