I’m trying to do something where: any time one of ...
# serialization
b
I’m trying to do something where: any time one of a subset of fields are changed in a class, I want to write a serialized version of that class to some store. I was looking at something like this:
Copy code
@Serializable
class Foo {
   var id: String by Delegates.observable("initialId", ::onChange)

   private fun onChange() {
      keyStore.set("foo", Json.encodeToString(this))
   }
}
but this won’t work because delegates don’t get serialized. Is there a good way to accomplish something like this?
o
You can introduce a backing property
_id
, which is then serialized, like so:
Copy code
import kotlinx.serialization.Serializable
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty

@Serializable
class Foo {
    private var _id: String = "initialId"  // <-- will be serialized
    var id: String by MyObservable<Foo, String>(this::_id, Foo::onChange)  // <- will not be serialized

    private fun onChange() {
        println("changed to $id")
    }
}

class MyObservable<in Owner, Value>(
    private var propertyReference: KMutableProperty0<Value>,
    val onChange: Owner.() -> Unit
) : ReadWriteProperty<Owner, Value> {

    override fun getValue(thisRef: Owner, property: KProperty<*>): Value = propertyReference.get()

    override fun setValue(thisRef: Owner, property: KProperty<*>, value: Value) {
        propertyReference.set(value)
        thisRef.onChange()
    }
}
b
Ah great, I’ll give that a shot, thank you!
👍 1