Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Created November 12, 2019 09:16
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 NikolaDespotoski/4e56223cafc62acc2f65c11816cfdb8f to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/4e56223cafc62acc2f65c11816cfdb8f to your computer and use it in GitHub Desktop.
abstract class LiveDataSharedPreferences<T>(val sharedPreferences: SharedPreferences,
val key: String,
val default: T) : MutableLiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onActive() {
super.onActive()
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onInactive() {
super.onInactive()
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
internal fun postWithouNotifyingChangeListeners(newValue: T) {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
postValue(newValue)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
}
class LiveDataSharedPreferencesInt(sharedPreferences: SharedPreferences, private val intKey: String,
private val defaultInt: Int) : LiveDataSharedPreferences<Int>(
sharedPreferences, intKey, defaultInt) {
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (intKey != key) {
return
}
val newValue = sharedPreferences.getInt(intKey, defaultInt)
postWithouNotifyingChangeListeners(newValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment