Last active
May 3, 2020 20:42
-
-
Save PetkevichPavel/b797ec65f0a9643a403f438fa7a39790 to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate getValue().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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