Skip to content

Instantly share code, notes, and snippets.

@C0DEbrained
Created November 11, 2024 12:49
Show Gist options
  • Select an option

  • Save C0DEbrained/71ec97c7e396906c7cd476c6fb57c371 to your computer and use it in GitHub Desktop.

Select an option

Save C0DEbrained/71ec97c7e396906c7cd476c6fb57c371 to your computer and use it in GitHub Desktop.
private object UninitializedValue
open class NullablePreferenceDelegate<T : @Serializable Any?>(
protected val montoya: MontoyaApi,
protected var key: String? = null,
protected val customSerializer: KSerializer<in T>? = null,
protected val default: () -> T?
) : ReadWriteProperty<Any?, T?> {
protected val preferences: Preferences = montoya.persistence().preferences()
private val json = Json { ignoreUnknownKeys = true }
private var _value: Any? = UninitializedValue
private var serializer: KSerializer<in T>? = null
init {
montoya.extension().registerUnloadingHandler { saveValue(_value as T) }
}
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
if (key == null) {
key = property.name
}
if (serializer == null) {
serializer = customSerializer ?: serializer(property.returnType)
}
if (_value == UninitializedValue) {
_value = loadValue()
}
return _value as T?
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
if (key == null) {
key = property.name
}
if (serializer == null) {
serializer = customSerializer ?: serializer(property.returnType)
}
this._value = value
if (value != null) saveValue(value)
}
protected open fun loadValue(): T? {
val value = preferences.getString(key!!)
val toReturn = if (value == null) {
default()
} else {
json.decodeFromString(serializer!!, value) as T
}
// println("Loading value ${this.key}: ${toReturn}")
return toReturn
}
internal fun saveValue(value: T) {
// println("Saving value ${this.key}: ${json.encodeToString(serializer!!, value)}")
preferences.setString(this.key, json.encodeToString(serializer!!, value))
}
}
open class PreferenceDelegate<T : @Serializable Any>(
montoya: MontoyaApi,
key: String? = null,
customSerializer: KSerializer<in T>? = null,
default: () -> T
) : NullablePreferenceDelegate<T>(montoya, key, customSerializer, default) {
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return super.getValue(thisRef, property)!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment