Skip to content

Instantly share code, notes, and snippets.

@jacobmoncur
Created January 26, 2016 07:20
Show Gist options
  • Save jacobmoncur/924797ffedbe07d4cd86 to your computer and use it in GitHub Desktop.
Save jacobmoncur/924797ffedbe07d4cd86 to your computer and use it in GitHub Desktop.
class Cacheable<T>(val key: String, val default: T, val valueSet: (value: T) -> Unit = {}) {
val type: Type = object : TypeToken<T>(){}.type
var value: T by Delegates.observable(default) { prop, old, new ->
new?.let { valueSet(it) }
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if(value == null) { value = Cacher.getFromCache(key, default, type) }
return value ?: default
}
operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T) {
this.value = Cacher.cache(key, value)
}
}
object Cacher {
lateinit var context: Context
lateinit var preferences: SharedPreferences
var gson = GsonBuilder().create()
fun initialize(context: Context, prefName: String = "${context.getPackageName()}_preferences", prefMode: Int = Context.MODE_PRIVATE){
this.context = context
preferences = Cacher.context.getSharedPreferences(prefName, prefMode)
}
@Suppress("UNCHECKED_CAST")
fun <T> getFromCache(key: String, default: T, type: Type): T = when {
default is Int -> preferences.getInt(key, default) as T
default is Long -> preferences.getLong(key, default) as T
default is Float -> preferences.getFloat(key, default) as T
default is Double -> preferences.getFloat(key, default.toFloat()) as T
default is Boolean -> preferences.getBoolean(key, false) as T
default is String -> preferences.getString(key, default) as T
else -> gson.fromJson(preferences.getString(key, null), type)
}
fun <T> cache(key: String, value: T): T {
if(!preferences.putAny(key, value)) preferences.putAny(key, gson.toJson(value))
return value
}
}
fun SharedPreferences.putAny(key: String, value: Any?): Boolean {
val editor = edit()
when(value){
is String -> editor.putString(key, value)
is Int -> editor.putInt(key, value)
is Long -> editor.putLong(key, value)
is Float -> editor.putFloat(key, value)
is Boolean -> editor.putBoolean(key, value)
is Double -> editor.putFloat(key, value.toFloat())
else -> return false
}
editor.apply()
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment