当前位置:   article > 正文

Android JetPack学习笔记-DataStore_androidx.datastore

androidx.datastore

        通过键值对存储,以异步、一致的事务方式存储数据克服了SharedPreferences的一些缺点,基于kotlin协程的Flow实现。并且可以对SP数据进行迁移。

        以protobuffer协议进行存储,速度更快,效率更高。

使用

        引用

  1. implementation "androidx.datastore:datastore-preferences:1.0.0-alpha05"
  2. implementation "androidx.datastore:datastore-preferences-core:1.0.0-alpha05"

        初始化

  1. private lateinit var dataStore : DataStore<Preferences>
  2. dataStore = context.createDataStore("huaStore")

        存数据

  1. private fun writeData() {
  2. runBlocking {
  3. //key为huahua value类型为int
  4. val key = preferencesKey<Int>("huahua")
  5. dataStore.edit {
  6. val value = it[key] ?: 0
  7. it[key] = value + 1
  8. }
  9. }
  10. }

        取数据

  1. private fun readData() = runBlocking {
  2. //key为huahua value类型为int
  3. val key = preferencesKey<Int>("huahua")
  4. var gaoxiao : Flow<Int> = dataStore.data.map {
  5. it[key] ?: 0
  6. }
  7. return@runBlocking gaoxiao.first()
  8. }

        清除数据

  1. private fun clearData() {
  2. runBlocking {
  3. dataStore.edit { //将该datastore中的数据全部清除
  4. it.clear()
  5. }
  6. }
  7. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/309325
推荐阅读
相关标签
  

闽ICP备14008679号