https://blog.youkuaiyun.com/github_35581409/article/details/142901840
看到在datastore上存储自定义的可序列化的对象
之前项目中用到过datastore的preference,当时官网的介绍是这样的
https://developer.android.com/topic/libraries/architecture/datastore?hl=zh-cn#prefs-vs-proto
初始化
// At the top level of your kotlin file: val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
写入
suspend fun incrementCounter() {
context.dataStore.edit { settings ->
val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
settings[EXAMPLE_COUNTER] = currentCounterValue + 1
}
}
读取
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[EXAMPLE_COUNTER] ?: 0
}
读取的时候,返回flow对象,虽然说可以随时监听啊,但是我只要当前的值,不需要监听怎么办呢
private suspend fun read(key: String): String? {
val dataStoreKey = preferencesKey<String>(key)
val preferences = dataStore.data.first()
return preferences[dataStoreKey]
}
直接返回first()就好了