Stephen Michel opened issue #1: Callbacks at Stephen Michel / android-utils

Stephen Michel
2019-02-09T21:17:18Z

There are two goals of KPreferences:

Reduce boilerplate. Without KPreferences, your config object would have

A val prefs = PreferenceManager.getSharedPreferences(…)

A lot of prefs.getType(context.getString(resId)) getters

A lot of prefs.edit().setType(context.getString(resId)).apply() setters

We can reduce this boilerplate by using Kotlin's delegated properties.

Provide a single point of truth for binding resource ids to types

If you change the type of data stored with a different key, the compiler won't warn you if you miss changing the type of prefs.getType call.

If you use a new key, to avoid having to migrate the old type, the compiler won't warn you if you still call the old type anywhere.

If you want to register an onSharedPreferenceChanged callback, you may have to do a type cast there, too, if you want to use the new value.

If you have a Config object with val myBool by BooleanPreference(R.id.myKey), those changes only have to be made once, and the compiler will warn you of anywhere relying on the old type.

That's all well and good, but we're missing a way to add and remove multiple onSharedPreferenceChanged callbacks -- ie, in different parts of the app -- while keeping the same advantages. Currently I'm working around this by just declaring one callback in a global Config object, and sending EventBus events. I'd love to be able to drop this and just use the callbacks directly from multiple places.