赞
踩
通过键值对存储,以异步、一致的事务方式存储数据克服了SharedPreferences的一些缺点,基于kotlin协程的Flow实现。并且可以对SP数据进行迁移。
以protobuffer协议进行存储,速度更快,效率更高。
- implementation "androidx.datastore:datastore-preferences:1.0.0-alpha05"
- implementation "androidx.datastore:datastore-preferences-core:1.0.0-alpha05"
- private lateinit var dataStore : DataStore<Preferences>
-
- dataStore = context.createDataStore("huaStore")
- private fun writeData() {
- runBlocking {
- //key为huahua value类型为int
- val key = preferencesKey<Int>("huahua")
- dataStore.edit {
- val value = it[key] ?: 0
- it[key] = value + 1
- }
- }
- }
- private fun readData() = runBlocking {
- //key为huahua value类型为int
- val key = preferencesKey<Int>("huahua")
- var gaoxiao : Flow<Int> = dataStore.data.map {
- it[key] ?: 0
- }
- return@runBlocking gaoxiao.first()
- }
- private fun clearData() {
- runBlocking {
- dataStore.edit { //将该datastore中的数据全部清除
- it.clear()
- }
- }
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。