Created
June 30, 2022 13:37
-
-
Save Astroa7m/75e96e3b244b5c3b66b255d238b51ca9 to your computer and use it in GitHub Desktop.
Preferences manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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