如何获取 Android Preferences DataStore 的所有键
How to get all keys of Android Preferences DataStore
如题所述,有没有办法获取Android Jetpack Preferences DataStore中存储的所有密钥,例如dataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
获取所有密钥
suspend fun Context.readAllKeys(): Set<Preferences.Key<*>>? {
val keys = dataStore.data
.map {
it.asMap().keys
}
return keys.firstOrNull()
}
通过它的键获取价值
suspend fun Context.getValueByKey(key: Preferences.Key<*>): Any? {
val value = dataStore.data
.map {
it[key]
}
return value.firstOrNull()
}
如题所述,有没有办法获取Android Jetpack Preferences DataStore中存储的所有密钥,例如dataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
获取所有密钥
suspend fun Context.readAllKeys(): Set<Preferences.Key<*>>? {
val keys = dataStore.data
.map {
it.asMap().keys
}
return keys.firstOrNull()
}
通过它的键获取价值
suspend fun Context.getValueByKey(key: Preferences.Key<*>): Any? {
val value = dataStore.data
.map {
it[key]
}
return value.firstOrNull()
}