Skip to content

Commit f33084d

Browse files
committed
chore: write example code for reducer over optional state
1 parent ea20153 commit f33084d

File tree

1 file changed

+64
-0
lines changed
  • composable-architecture/src/test/kotlin/composablearchitecture/sandbox/optional

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package composablearchitecture.sandbox.optional
2+
3+
import arrow.optics.Prism
4+
import arrow.optics.optics
5+
import composablearchitecture.Reducer
6+
import composablearchitecture.Store
7+
import composablearchitecture.withNoEffect
8+
import kotlinx.coroutines.flow.collect
9+
import kotlinx.coroutines.launch
10+
import kotlinx.coroutines.runBlocking
11+
import kotlinx.coroutines.test.TestCoroutineDispatcher
12+
13+
@optics
14+
data class AppState(val text: String? = null) {
15+
companion object
16+
}
17+
18+
sealed class AppAction {
19+
data class UpdateText(val to: String) : AppAction()
20+
}
21+
22+
val optionalReducer = Reducer<String, AppAction, Unit> { _, action, _ ->
23+
when (action) {
24+
is AppAction.UpdateText -> action.to.withNoEffect()
25+
}
26+
}.optional()
27+
28+
val appReducer: Reducer<AppState, AppAction, Unit> = optionalReducer.pullback(
29+
toLocalState = AppState.nullableText,
30+
toLocalAction = Prism.id(),
31+
toLocalEnvironment = { Unit }
32+
)
33+
34+
fun main() {
35+
runBlocking {
36+
val testDispatcher = TestCoroutineDispatcher()
37+
38+
println("🎬 initial state is non-null")
39+
40+
var store = Store(
41+
initialState = AppState(text = ""),
42+
reducer = appReducer,
43+
environment = Unit,
44+
mainDispatcher = testDispatcher
45+
)
46+
var job = launch(testDispatcher) { store.states.collect { println(it) } }
47+
store.send(AppAction.UpdateText("Update non-null state"))
48+
job.cancel()
49+
50+
println("🎬 initial state is null")
51+
52+
store = Store(
53+
initialState = AppState(text = null),
54+
reducer = appReducer,
55+
environment = Unit,
56+
mainDispatcher = testDispatcher
57+
)
58+
job = launch(testDispatcher) { store.states.collect { println(it) } }
59+
store.send(AppAction.UpdateText("Update null state"))
60+
job.cancel()
61+
62+
println("")
63+
}
64+
}

0 commit comments

Comments
 (0)