Skip to content

Commit f542cca

Browse files
hardysimwkornewald
andauthored
childReactiveState for child events (#43)
* childReactiveState for child events * Apply suggestions from code review Co-authored-by: Waldemar Kornewald <[email protected]> * add childReactiveStateBase() --------- Co-authored-by: Waldemar Kornewald <[email protected]>
1 parent e5fc1ef commit f542cca

File tree

1 file changed

+24
-2
lines changed
  • reactivestate-core/src/commonMain/kotlin/com/ensody/reactivestate

1 file changed

+24
-2
lines changed

reactivestate-core/src/commonMain/kotlin/com/ensody/reactivestate/ReactiveState.kt

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ public open class BaseReactiveState<E : ErrorEvents>(final override val scope: C
9696
* }
9797
* ```
9898
*/
99-
public fun <E : ErrorEvents, P : ReactiveState<out E>, RS : ReactiveState<E>> P.childReactiveState(
99+
private fun <E : ErrorEvents, P : ReactiveState<*>, RS : ReactiveState<E>> P.childReactiveStateBase(
100+
eventHandler: suspend (child: RS) -> Unit,
100101
block: () -> RS,
101102
): ReadOnlyProperty<Any?, RS> {
102103
val child = block()
@@ -106,13 +107,34 @@ public fun <E : ErrorEvents, P : ReactiveState<out E>, RS : ReactiveState<E>> P.
106107
}
107108
}
108109
launch(withLoading = null) {
109-
eventNotifier.emitAll(child.eventNotifier)
110+
eventHandler(child)
110111
}
111112
(this as? OnReactiveStateAttached)?.onReactiveStateAttached(child)
112113
(child as? OnReactiveStateAttachedTo)?.onReactiveStateAttachedTo(this)
113114
return WrapperProperty(child)
114115
}
115116

117+
/**
118+
* Uses [childReactiveStateBase] and emits events from the child to the parent ReactiveState.
119+
*/
120+
public fun <E : ErrorEvents, P : ReactiveState<out E>, RS : ReactiveState<E>> P.childReactiveState(
121+
block: () -> RS,
122+
): ReadOnlyProperty<Any?, RS> = childReactiveStateBase(
123+
eventHandler = { child -> eventNotifier.emitAll(child.eventNotifier) },
124+
block = block,
125+
)
126+
127+
/**
128+
* Uses [childReactiveStateBase] and emits events from the child to the given [eventHandler].
129+
*/
130+
public fun <E : ErrorEvents, P : ReactiveState<*>, RS : ReactiveState<E>> P.childReactiveState(
131+
eventHandler: E,
132+
block: () -> RS,
133+
): ReadOnlyProperty<Any?, RS> = childReactiveStateBase(
134+
eventHandler = { child -> child.eventNotifier.handleEvents(eventHandler) },
135+
block = block,
136+
)
137+
116138
/** Just wraps an eagerly computed value in a property to allow `val foo by bar` notation. */
117139
private class WrapperProperty<T>(val data: T) : ReadOnlyProperty<Any?, T> {
118140
override fun getValue(thisRef: Any?, property: KProperty<*>): T = data

0 commit comments

Comments
 (0)