I’m looking to read my DataStore for Feature Flags I have saved there. DataStore returns a flow, which makes sense but I do really need to read it once at the moment. No fancy logic. Listening to live changes is less important right now but might be in the future.
What happens is, when I try to read the data, it gets stuck somewhere as if my function never emitted values.
Here’s the code:
The actual read from data store
fun getDataOrDefault(key: String, defaultValue: Boolean): Flow<Boolean> =
dataStore.data
.catch { exception ->
when (exception) {
is IOException -> emit(emptyPreferences())
else -> throw exception
}
}.map { pref ->
pref[booleanPreferencesKey(key)] ?: defaultValue
}
Now, I have a list of keys that I want to pass and read values for
Read multiple values
fun getBoolEntries(vararg keys: String): Flow<Pair<String, Boolean>> = flow {
keys.forEach { emit(it) }
}.onEach {
Log.i("DBGG", "Key: $it")
}.flatMapMerge { key ->
getDataOrDefaultOrDefault(key, false).map { Pair(key, it) }
}
ViewModel read
viewModelScope.launch {
val flags = dataStoreRepository.getBoolEntries(
KEY_1,
KEY_2,
KEY_3,//... and so on
).flowOn(Dispatchers.IO).toList()
_viewState.emit(
ConfigState.Active(flags)
)
}
It never finishes and I can’t emit a new state. What am I missing?