Opto

A lightweight Preferences DataStore wrapper.

Creator

View on GitHub

Opto is a lightweight wrapper for Preferences DataStore that I use in my projects. It offers a class that represents a single preference, convenience functions for creating instances of this class, and utilities that simplify reading and updating the values of preferences. The library also helps convert values of complex data types to types supported by Preferences DataStore.

class PreferenceManager @Inject constructor(
override val preferencesDataStore: DataStore<Preferences>,
) : PreferenceManager() {
val booleanPreference = preference(
key = booleanPreferencesKey(name = "boolean_preference"),
defaultValue = false,
)
val enumPreference = preference(
key = stringPreferencesKey(name = "enum_preference"),
defaultValue = Theme.Light,
save = { theme -> theme.name },
parse = Theme::valueOf,
)
}

The Preference#get function returns a Flow:

booleanPreference.get()

Preference#onEach helps respond to changes to the values of preferences:

booleanPreference.onEach(launchIn = viewModelScope) { booleanPreferenceValue ->
...
}

Preferences can be updated via Preference#set, which is a suspending function:

enumPreference.set(value = Theme.Dark)

Multiple convenience functions are included in the library. For example, boolean preferences can be easily toggled:

booleanPreference.toggle()

Opto is separated into three modules: domain, core, and compose.

© 2018–2022 Patryk Michalik

[GitHub, Telegram, Twitter]