Skip to content

Instantly share code, notes, and snippets.

@drstranges
Last active June 26, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drstranges/5898ef4e3d6c9705d3cd84c650b4396c to your computer and use it in GitHub Desktop.
Save drstranges/5898ef4e3d6c9705d3cd84c650b4396c to your computer and use it in GitHub Desktop.
val lastSyncTime = prefs.asLiveData(PREFKEY_LAST_SYNC_TIME, 0L)
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import androidx.lifecycle.LiveData
class SharedPreferenceLiveData<T>(
val prefs: SharedPreferences,
val key: String,
val defaultValue: T,
val valueProvider: (prefs: SharedPreferences, key: String, defValue: T?) -> T?
) : LiveData<T>() {
private val onChangeListener = OnSharedPreferenceChangeListener { sharedPrefs, key ->
if (key == this.key) value = valueProvider(sharedPrefs, key, defaultValue)
}
override fun onActive() {
super.onActive()
value = valueProvider(prefs, key, defaultValue)
prefs.registerOnSharedPreferenceChangeListener(onChangeListener)
}
override fun onInactive() {
prefs.unregisterOnSharedPreferenceChangeListener(onChangeListener)
super.onInactive()
}
}
inline fun <reified T : Any> SharedPreferences.asLiveData(key: String, defaultValue: T?): LiveData<T?> =
SharedPreferenceLiveData(this, key, defaultValue, getValueProvider(T::class))
@Suppress("UNCHECKED_CAST")
fun <T : Any> getValueProvider(clazz: KClass<T>): ((prefs: SharedPreferences, key: String, defValue: T?) -> T?) =
when (clazz) {
String::class -> { pref, key, defValue -> pref.getString(key, defValue as? String) as T? }
Boolean::class -> { pref, key, defValue -> pref.getBoolean(key, true == defValue) as T? }
Int::class -> { pref, key, defValue -> pref.getInt(key, defValue as? Int ?: 0) as T? }
Long::class -> { pref, key, defValue -> pref.getLong(key, defValue as? Long ?: 0L) as T? }
Float::class -> { pref, key, defValue -> pref.getFloat(key, defValue as? Float ?: 0f) as T? }
else -> throw UnsupportedOperationException("Type $clazz is not supported!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment