From ef1abc3b975e1c77fc8663c5e5e95769fc934551 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Wed, 20 May 2020 17:12:56 +0200 Subject: Make all stateful components implement ObservableState interface --- .../src/main/kotlin/pl/treksoft/kvision/react/React.kt | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'kvision-modules/kvision-react/src') diff --git a/kvision-modules/kvision-react/src/main/kotlin/pl/treksoft/kvision/react/React.kt b/kvision-modules/kvision-react/src/main/kotlin/pl/treksoft/kvision/react/React.kt index 7424159f..79f4d1a0 100644 --- a/kvision-modules/kvision-react/src/main/kotlin/pl/treksoft/kvision/react/React.kt +++ b/kvision-modules/kvision-react/src/main/kotlin/pl/treksoft/kvision/react/React.kt @@ -27,6 +27,7 @@ import org.w3c.dom.HTMLElement import pl.treksoft.kvision.KVManagerReact import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.Widget +import pl.treksoft.kvision.state.ObservableState import pl.treksoft.kvision.utils.set import react.RBuilder import react.dom.render as ReactRender @@ -41,12 +42,15 @@ class React( state: S, classes: Set = setOf(), private val builder: RBuilder.(getState: () -> S, changeState: ((S) -> S) -> Unit) -> Unit -) : Widget(classes) { +) : Widget(classes), ObservableState { + + private val observers = mutableListOf<(S) -> Unit>() var state = state set(value) { field = value refreshFunction?.invoke() + observers.forEach { it(state) } } private var refreshFunction: (() -> Unit)? = null @@ -76,6 +80,16 @@ class React( KVManagerReact.reactDom.unmountComponentAtNode(it) } } + + override fun getState(): S = state + + override fun subscribe(observer: (S) -> Unit): () -> Unit { + observers += observer + observer(state) + return { + observers -= observer + } + } } /** -- cgit