通过键值对存储,以异步、一致的事务方式存储数据克服了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()
}
}
}