Patrick Michalik

Opto

A light Preferences DataStore wrapper.

Kotlin
View on GitHub

Opto is a lightweight wrapper for Preferences DataStore. Its two main APIs are PreferenceImpl, which implements the Preference interface, and PreferenceManager. By implementing the PreferenceManager interface, one can create a class responsible for handling settings:

class PreferenceManager @Inject constructor(
    override val preferencesDataStore: DataStore<Preferences>,
) : PreferenceManager {
 
    val notificationsEnabled = preference(
        key = booleanPreferencesKey("notifications_enabled"),
        defaultValue = false,
    )
 
    val theme = preference(
        key = stringPreferencesKey("theme"),
        defaultValue = Theme.Light,
        serialize = { it.name },
        deserialize = Theme::valueOf,
    )
}

PreferenceImpl has two main functions: get and set. The former returns a Flow instance, enabling you to use Flow#map, Flow#onEach, and the like. The latter is a suspending function. Opto supports serialization, which is useful for non-primitive data types.

© 2018–2024 Patrick Michalik