Read Data from DataStore
In this section, you’ll learn how to read data from DataStore.
DataStore exposes a data
property that returns a Flow<Preferences>
. This ensures you can observe changes to the data stored in DataStore. You use the key you created the data with to read the data from DataStore. An example of reading data from DataStore is shown below:
fun getSelectedFilter(): Flow<String> {
return context.dataStore.data
.map { preferences ->
preferences[stringPreferencesKey("filters")] ?: "All"
}
}
In the above example, you call context.dataStore.data
, which returns a Flow<Preferences>
. You then call map
on the Flow<Preferences>
to map the Preferences
to a String
for your specified key. You then return the selected filter from DataStore. You get the value of the key you created using the stringPreferencesKey()
function. This key is used to get the selected filter from DataStore. You return “All” as the default filter if the selected filter isn’t found. The Flow will always emit the latest value stored in DataStore or throw an exception if an error occurs when reading the data.
To handle errors while reading data from DataStore, you use the catch
operator before the map
operator and emit empty data as shown below:
fun getSelectedFilter(): Flow<String> {
return context.dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
preferences[stringPreferencesKey("filters")] ?: "All"
}
}