JetPack-DataStore初体验

Jetpack DataStore是一种数据存储解决方案,允许您使用协议缓冲区存储键值对或类型化的对象。 DataStore使用Kotlin协程和Flow来存储数据,如果目前使用的是SharedPreferences,可以考虑迁移到DataStore。

官方文档直达

DataStore提供了两种不同的实现:Preferences DataStore和Proto DataStore。

  • Preferences DataStore:以键值对的形式存储在本地和 SharedPreferences 类似,但是 DataStore 是基于 Flow 实现的,不会阻塞主线程,并且保证类型安全。

  • Proto DataStore:存储类的对象(typed objects ),通过 protocol buffers 将对象序列化存储在本地,protocol buffers 现在已经应用的非常广泛,无论是微信还是阿里等等大厂都在使用,我们在部分业务场景中也用到了 protocol buffers。

本篇文章简单介绍第一种Preferences DataStore的使用方法。

一、在app下的build.gradle注入依赖

    // Preferences DataStore
    implementation "androidx.datastore:datastore-preferences:1.0.0-alpha02"
    // Proto DataStore
    implementation "androidx.datastore:datastore-core:1.0.0-alpha02"

二、创建Preferences DataStore

 private val dataStore: DataStore<Preferences> = this.createDataStore(
        name = "Data"
    )

三、从Preferences DataStore读取数据

val dataFlow: Flow<String> = dataStore.data
                    .map { preferences ->
                        // No type safety.
                        preferences[dataStoreKey] ?: ""
                    }
                dataFlow.collect { value -> println(value) }

四、存入数据到Preferences DataStore

suspend fun saveData() {
        dataStore.edit { settings ->
//            val currentCounterValue = settings[dataStoreKey] ?: ""
            settings[dataStoreKey] = "我是存入的数据"+System.currentTimeMillis()
        }
    }

此文只介绍了Preferences DataStore的简单使用,还在研究中,后期继续完善。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值