Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Last active May 3, 2020 20:42
Show Gist options
  • Save PetkevichPavel/b797ec65f0a9643a403f438fa7a39790 to your computer and use it in GitHub Desktop.
Save PetkevichPavel/b797ec65f0a9643a403f438fa7a39790 to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate getValue().
open class PreferencesDelegate<T>(private val key: String) {
private var variable: Any? = null
private var initialized = false
/**
* Return desired value by a given key. Performing operation 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.
* @return T - T or null.
*/
open operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
if (thisRef !is SharedPreferencesProvider)
throw RuntimeException("Please check if your manager implementation class implement SharedPreferencesProvider interface.")
synchronized(this) {
if (!initialized) {
variable = thisRef.preferences.all[key] as? T
initialized = true
}
return variable as? T
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment