Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Created May 3, 2020 21:35
Show Gist options
  • Save PetkevichPavel/babab1174426d58352e9b3672df94bdb to your computer and use it in GitHub Desktop.
Save PetkevichPavel/babab1174426d58352e9b3672df94bdb to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate setValue.
open class PreferencesDelegate<T>(private val key: String) {
private var variable: Any? = null
private var initialized = false
/**
* Saves given value to SharedPreferences on synchronized thread.
* @param thisRef - is the reference to the class that contains the property
* @param property - is an instance of the [KProperty] class, which contains metadata.
*/
open operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (thisRef !is SharedPreferencesProvider)
throw RuntimeException("Please check if your manager implementation class implement SharedPreferencesProvider interface.")
synchronized(this) {
if (variable == value) return
variable = value
thisRef.preferences.edit()?.apply {
value?.takeIf { it != null }?.apply {
putAny(key, value)
} ?: remove(key)
}?.apply()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment