How to get all keys of Android Preferences DataStore

2k Views Asked by At

As mentioned by the title, is there any way to obtain all the keys stored in an Android Jetpack Preferences DataStore, e.g., dataStore

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
1

There are 1 best solutions below

0
On BEST ANSWER

For getting all keys

suspend fun Context.readAllKeys(): Set<Preferences.Key<*>>? {
    val keys = dataStore.data
        .map {
           it.asMap().keys
        }
    return keys.firstOrNull()
}

for getting value by it's key

suspend fun Context.getValueByKey(key: Preferences.Key<*>): Any? {
    val value = dataStore.data
        .map {
            it[key]
        }
    return value.firstOrNull()
}