Skip to content

Instantly share code, notes, and snippets.

@lucassales2
Forked from rharter/SharedPreferenceLiveData.kt
Last active August 4, 2020 13:44
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 lucassales2/de467a4741353b8c9ca94ea93c8bbfd8 to your computer and use it in GitHub Desktop.
Save lucassales2/de467a4741353b8c9ca94ea93c8bbfd8 to your computer and use it in GitHub Desktop.
Creates LiveData objects that observe a value in SharedPreferences while they have active listeners.
// 1. Get a reference to SharedPreferences however you normally would.
val prefs: SharedPreferences
// 2. Use the extension functions to create a LiveData object of whatever type you need and observe the result.
prefs.liveData("analytics_enabled", false).observe(this, { enabled ->
if (enabled != null && enabled) {
sendAnalytics()
}
})
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
abstract class SharedPreferenceLiveData<T>(
val sharedPrefs: SharedPreferences,
val key: String,
val defValue: T
) : LiveData<T>() {
private val preferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == this.key) {
value = getValueFromPreferences(key, defValue)
}
}
abstract fun getValueFromPreferences(key: String, defValue: T): T
override fun onActive() {
super.onActive()
value = getValueFromPreferences(key, defValue)
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
}
override fun onInactive() {
sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener)
super.onInactive()
}
}
inline fun <reified T> SharedPreferences.liveData(
key: String,
default: T
): SharedPreferenceLiveData<T> {
@Suppress("UNCHECKED_CAST")
return object : SharedPreferenceLiveData<T>(this, key, default) {
override fun getValueFromPreferences(key: String, defValue: T): T {
return when (default) {
is String -> getString(key, default) as T
is Int -> getInt(key, default) as T
is Long -> getLong(key, default) as T
is Boolean -> getBoolean(key, default) as T
is Float -> getFloat(key, default) as T
is Set<*> -> getStringSet(key, default as Set<String>) as T
is MutableSet<*> -> getStringSet(key, default as MutableSet<String>) as T
else -> throw IllegalArgumentException("generic type not handled")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment