Created
May 3, 2020 21:35
-
-
Save PetkevichPavel/babab1174426d58352e9b3672df94bdb to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate setValue.
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 | |
/** | |
* 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