Add mutableCollectionState and docs.

This commit is contained in:
2022-01-16 14:50:58 +01:00
parent ebb8e9a3c5
commit 0b12c37558
7 changed files with 226 additions and 11 deletions

View File

@@ -0,0 +1,54 @@
package nl.astraeus.komp
inline fun <reified T> Komponent.mutableCollectionState(
initialValue: MutableCollection<T>
): MutableCollection<T> = MutableCollectionStateDelegate(
this,
initialValue
)
class MutableCollectionStateDelegate<T>(
val komponent: Komponent,
val collection: MutableCollection<T>
): MutableCollection<T> by collection {
override fun add(element: T): Boolean {
komponent.requestUpdate()
return collection.add(element)
}
override fun addAll(elements: Collection<T>): Boolean {
komponent.requestUpdate()
return collection.addAll(elements)
}
override fun clear() {
komponent.requestUpdate()
collection.clear()
}
// todo: return iterator wrapper to update at changes?
// override fun iterator(): MutableIterator<T> = collection.iterator()
override fun remove(element: T): Boolean {
komponent.requestUpdate()
return collection.remove(element)
}
override fun removeAll(elements: Collection<T>): Boolean {
komponent.requestUpdate()
return collection.removeAll(elements)
}
override fun retainAll(elements: Collection<T>): Boolean {
komponent.requestUpdate()
return collection.retainAll(elements)
}
}

View File

@@ -2,20 +2,41 @@ package nl.astraeus.komp
import kotlin.reflect.KProperty
class StateDelegate<T>(
val komponent: Komponent,
initialValue: T
) {
var value: T = initialValue
interface Delegate<T> {
operator fun getValue(
thisRef: Any?,
property: KProperty<*>
): T
operator fun setValue(
thisRef: Any?,
property: KProperty<*>,
value: T
)
}
open class StateDelegate<T>(
val komponent: Komponent,
initialValue: T
) : Delegate<T> {
private var value: T = initialValue
init {
if (value is MutableCollection<*>) {
error("Use mutableList to create a collection!")
}
}
override operator fun getValue(
thisRef: Any?,
property: KProperty<*>
): T {
return value
}
operator fun setValue(
override operator fun setValue(
thisRef: Any?,
property: KProperty<*>,
value: T
@@ -29,7 +50,7 @@ class StateDelegate<T>(
inline fun <reified T> Komponent.state(
initialValue: T
): StateDelegate<T> = StateDelegate(
this,
initialValue
)
): Delegate<T> = StateDelegate(
this,
initialValue
)