Sto cercando di costruire una classe in cui certi valori sono Osservabili, ma anche Serializable.
Questo, ovviamente, le opere e la serializzazione funziona, ma è molto standard-pesante dover aggiungere un setter per ogni singolo campo e manualmente dover chiamare change(...)
all'interno di ogni setter:
interface Observable {
fun change(message: String) {
println("changing $message")
}
}
@Serializable
class BlahVO : Observable {
var value2: String = ""
set(value) {
field = value
change("value2")
}
fun toJson(): String {
return Json.encodeToString(serializer(), this)
}
}
println(BlahVO().apply { value2 = "test2" })
correttamente uscite
changing value2
{"value2":"test2"}
Ho cercato di introdurre i partecipanti:
interface Observable {
fun change(message: String) {
println("changing $message")
}
@Suppress("ClassName")
class default<T>(defaultValue: T) {
private var value: T = defaultValue
operator fun getValue(observable: Observable, property: KProperty<*>): T {
return value
}
operator fun setValue(observable: Observable, property: KProperty<*>, value: T) {
this.value = value
observable.change(property.name)
}
}
}
@Serializable
class BlahVO : Observable {
var value1: String by Observable.default("value1")
fun toJson(): String {
return Json.encodeToString(serializer(), this)
}
}
println(BlahVO().apply { value1 = "test1" })
scattare correttamente il rilevamento delle modifiche, ma non serializzare:
changing value1
{}
Se vado da Osservabile ReadWriteProperty,
interface Observable {
fun change(message: String) {
println("changing $message")
}
fun <T> look(defaultValue: T): ReadWriteProperty<Observable, T> {
return OP(defaultValue, this)
}
class OP<T>(defaultValue: T, val observable: Observable) : ObservableProperty<T>(defaultValue) {
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
super.setValue(thisRef, property, value)
observable.change("blah!")
}
}
}
@Serializable
class BlahVO : Observable {
var value3: String by this.look("value3")
fun toJson(): String {
return Json.encodeToString(serializer(), this)
}
}
il risultato è lo stesso:
changing blah!
{}
Allo stesso modo per i Delegati.vetoable
var value4: String by Delegates.vetoable("value4", {
property: KProperty<*>, oldstring: String, newString: String ->
this.change(property.name)
true
})
uscite:
changing value4
{}
I delegati non sembra di lavorare con Kotlin Serializzazione
Quali altre opzioni ci sono per osservare una struttura a modifiche senza rompere la sua serializzazione che funziona anche su altre piattaforme (KotlinJS, KotlinJVM, Android, ...)?