Fonament Preferences
The fonament preferences is an API that provides functions to store and retrieve data from DataStore Preferences.
FonamentPreferences: The class that provides functions to set and get data from aDataStore<Preferences>instance.FonamentPreferencesFactory: The factory for creatingFonamentPreferencesinstances.FonamentPreferencesDataStoreSingleton: The class that creates aDataStoreinstance for a given file name as a singleton.
Usage: without DI
You can crete a FonamentPreferences instance using the FonamentPreferencesFactory class.
val fonamentPreferences = FonamentPreferencesFactory().create("YOUR_DATASTORE_PREFERENCES_FILE_NAME")
// ℹ️ It is not necessary to specify the file format extension .preferences_pb in the create(name).
Info
FonamentPreferencesFactory uses FonamentPreferencesDataStoreSingleton to create a DataStore instance for a given file name as a singleton to avoid:
Android
FonamentPreferencesFactory needs a Context instance to create the FonamentPreferences.
Using FonamentPreferences instance
class UserPreferencesRepository(
private val preferences: FonamentPreferences,
) {
fun getUserTheme(): Flow<AppTheme> =
preferences.getInt(APP_THEME_KEY).map { theme ->
// ...
}
suspend fun setUserTheme(theme: AppTheme) {
preferences[APP_THEME_KEY] = theme.ordinal
}
}
Usage: with DI
:fonament-preferences:di provides a subset of modules to create and inject a FonamentPreferences instance.
Koin
Create a FonamentPreferences instance using Koin.
Android
Remember to inject the Android context via androidContext.