https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
d

Daniel

12/25/2019, 10:21 PM
Thoughts on the SharedPreferences component needed: Would you prefer a single class where all shared preferences are located (see example below) or would you have several classes which handle a subset of preferences? Or even several shared preferences? Currently thinking about the pros and cons of each and I am leaning to a single class. Since there I am sure that there are never duplicate keys (because they are not scattered over several classes) and I can immedeately say what the application saves in the preferences.
Copy code
class Preferences(private val sharedPreferences: SharedPreferences) {
    private companion object {
        private const val GENERATED_LEVEL_INFO_SEEN_KEY =
                "generatedLevelInfoSeenKey"

       // ...
    }

    var generatedLevelInfoSeen by BooleanPreference(
            GENERATED_LEVEL_INFO_SEEN_KEY, false)

    // ...

    private inner class BooleanPreference(
            private val key: String,
            private val default: Boolean) {

        operator fun getValue(thisRef: Preferences, property: KProperty<*>) =
                sharedPreferences.getBoolean(key, default)

        operator fun setValue(thisRef: Preferences, property: KProperty<*>, value: Boolean) =
                sharedPreferences.edit { putBoolean(key, value) }
    }
}
p

Pablichjenkov

12/25/2019, 10:45 PM
I like better the second approach. Each module or manager class knows its preferences values. The way I use it is like an abstract storage layer implementation. My Managers, Loaders or Helper classes don't know about it. They just see a Persistent Storage API, regardless what backs it up.
1
a

Anastasia Finogenova

12/26/2019, 3:07 AM
I prefer the single class approach with a possible abstract facade if you prefer
d

Daniel

12/26/2019, 12:20 PM
Thanks you both! Hard to pick a clear winner I think
3 Views