Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Last active May 3, 2020 20:39
Show Gist options
  • Save PetkevichPavel/3768dff7eb5e041bcdd8437b56bf9c7b to your computer and use it in GitHub Desktop.
Save PetkevichPavel/3768dff7eb5e041bcdd8437b56bf9c7b to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate without implementation.
open class PreferencesDelegate<T>(private val key: String) {
private var variable: Any? = null
/**
* 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 - desired value by a given key or null.
*/
open operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
//...nothing for now
}
/**
* 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) {
//...nothing for now
}
/**
* Add [resetCache] into specific [cacheCleaners].
* @return - PreferencesDelegate<T>.
*/
fun addCacheCleaners(cacheCleaners: MutableList<(() -> Unit)>) = apply {
cacheCleaners.add { this.resetCache() }
}
/**
* Clear cached value.
*/
private fun resetCache() {
variable = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment