From 18af38d4ac7bbc33a43115c99ed47a586acf6020 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Wed, 20 May 2020 18:26:12 +0200 Subject: Add stateFlow extension property for an ObservableState. --- .../kotlin/pl/treksoft/kvision/event/EventFlow.kt | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'kvision-modules/kvision-event-flow/src/main/kotlin') diff --git a/kvision-modules/kvision-event-flow/src/main/kotlin/pl/treksoft/kvision/event/EventFlow.kt b/kvision-modules/kvision-event-flow/src/main/kotlin/pl/treksoft/kvision/event/EventFlow.kt index f9556e62..dc40beba 100644 --- a/kvision-modules/kvision-event-flow/src/main/kotlin/pl/treksoft/kvision/event/EventFlow.kt +++ b/kvision-modules/kvision-event-flow/src/main/kotlin/pl/treksoft/kvision/event/EventFlow.kt @@ -24,11 +24,17 @@ package pl.treksoft.kvision.event import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.callbackFlow import org.w3c.dom.events.Event import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.core.onEvent +import pl.treksoft.kvision.state.ObservableState +/** + * Extension property returning Flow> for a given event + */ @OptIn(ExperimentalCoroutinesApi::class) inline fun T.eventFlow(event: String): Flow> = callbackFlow { val id = onEvent { @@ -41,6 +47,9 @@ inline fun T.eventFlow(event: String): Flow> } } +/** + * Extension property returning Flow for a click event. + */ @OptIn(ExperimentalCoroutinesApi::class) inline val T.clickFlow: Flow get() = callbackFlow { @@ -54,6 +63,9 @@ inline val T.clickFlow: Flow } } +/** + * Extension property returning Flow for an input event. + */ @OptIn(ExperimentalCoroutinesApi::class) inline val T.inputFlow: Flow get() = callbackFlow { @@ -67,6 +79,9 @@ inline val T.inputFlow: Flow } } +/** + * Extension property returning Flow for a change event. + */ @OptIn(ExperimentalCoroutinesApi::class) inline val T.changeFlow: Flow get() = callbackFlow { @@ -79,3 +94,12 @@ inline val T.changeFlow: Flow removeEventListener(id) } } + +/** + * Extension property returning StateFlow for an ObservableState. + */ +@OptIn(ExperimentalCoroutinesApi::class) +inline val ObservableState.stateFlow: StateFlow + get() = MutableStateFlow(getState()).apply { + this@stateFlow.subscribe { this.value = it } + } -- cgit