Skip to content

Commit 10c890f

Browse files
committed
Provide refactoring
1 parent 0ca69b2 commit 10c890f

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

example/src/main/kotlin/feature/Feature.kt

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,46 @@ package feature
22

33
import kotlinx.coroutines.CoroutineScope
44
import kotlinx.coroutines.Dispatchers
5-
import kotlinx.coroutines.SupervisorJob
65
import kotlinx.coroutines.cancel
76
import kotlinx.coroutines.channels.Channel
7+
import kotlinx.coroutines.channels.consumeEach
88
import kotlinx.coroutines.flow.MutableStateFlow
99
import kotlinx.coroutines.flow.asStateFlow
1010
import kotlinx.coroutines.flow.receiveAsFlow
11+
import kotlinx.coroutines.launch
1112

12-
abstract class Feature<in Command, State, Event>(
13+
abstract class Feature<Command, State, Event>(
1314
initialState: State,
1415
private val reducer: Reducer<Command, State, Event>,
1516
) {
16-
val featureScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
17+
internal val coroutineScope = CoroutineScope(Dispatchers.Default)
18+
19+
private val commands: Channel<Command> = Channel(Channel.UNLIMITED)
1720

1821
private val _state = MutableStateFlow(initialState)
22+
1923
val state = _state.asStateFlow()
2024

2125
private val _events = Channel<Event>(Channel.BUFFERED)
26+
2227
val events = _events.receiveAsFlow()
2328

24-
suspend fun execute(command: Command) = runCatching {
25-
val (newState, events) = reducer.reduce(_state.value, command)
29+
init {
30+
coroutineScope.launch {
31+
commands.consumeEach { command ->
32+
val (newState, newEvents) = reducer.reduce(_state.value, command)
33+
34+
_state.value = newState
2635

27-
_state.emit(newState)
36+
newEvents.forEach { event ->
37+
_events.send(event)
38+
}
39+
}
40+
}
41+
}
2842

29-
events.forEach { event -> _events.send(event) }
43+
suspend fun execute(command: Command) = runCatching {
44+
commands.send(command)
3045
}.isSuccess
3146

3247
open fun <Command, State, Event> Feature<Command, State, Event>.invokeOnClose(block: () -> Unit = {}) {
@@ -37,7 +52,11 @@ abstract class Feature<in Command, State, Event>(
3752
try {
3853
invokeOnClose()
3954
} finally {
40-
featureScope.cancel()
55+
coroutineScope.cancel()
56+
57+
commands.close()
58+
59+
_events.close()
4160
}
4261
}
4362
}

0 commit comments

Comments
 (0)