Skip to content

Instantly share code, notes, and snippets.

@Astroa7m
Created June 30, 2022 13:37
Show Gist options
  • Save Astroa7m/75e96e3b244b5c3b66b255d238b51ca9 to your computer and use it in GitHub Desktop.
Save Astroa7m/75e96e3b244b5c3b66b255d238b51ca9 to your computer and use it in GitHub Desktop.
Preferences manager
class PreferencesManager(
private val application: Application,
) {
private companion object{
val Context.pref: DataStore<Preferences> by preferencesDataStore(
name = "pref_settings"
)
}
val imageCategoryPref = application.applicationContext.pref.data
.catch { e ->
if (e is IOException)
emit(emptyPreferences())
else
throw e
}.map { preferences ->
val imageCategory = preferences[intPreferencesKey(IMAGE_CATEGORY)] ?: categories.lastIndex
imageCategory
}
suspend fun setImageCategory(categoryIndex: Int) {
application.applicationContext.pref.edit { preferences ->
preferences[intPreferencesKey(IMAGE_CATEGORY)] = categoryIndex
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment