|
1 | 1 | package me.pavi2410.useCompose.app.screens
|
2 | 2 |
|
3 | 3 | import androidx.compose.foundation.layout.Column
|
| 4 | +import androidx.compose.foundation.layout.padding |
4 | 5 | import androidx.compose.material.Button
|
5 | 6 | import androidx.compose.material.Text
|
6 | 7 | import androidx.compose.runtime.Composable
|
| 8 | +import androidx.compose.ui.Modifier |
| 9 | +import androidx.compose.ui.tooling.preview.Preview |
| 10 | +import androidx.compose.ui.unit.dp |
7 | 11 | import me.pavi2410.useCompose.react.useReducer
|
8 | 12 |
|
9 | 13 | data class MyState(val count: Int)
|
10 |
| -data class MyAction(val type: String) |
| 14 | +sealed interface MyAction { |
| 15 | + object Increment : MyAction |
| 16 | + object Decrement : MyAction |
| 17 | +} |
11 | 18 |
|
12 | 19 | val initialState = MyState(0)
|
13 | 20 |
|
| 21 | +@Preview(showBackground = true) |
14 | 22 | @Composable
|
15 | 23 | fun ReducerExample() {
|
16 |
| - Column { |
| 24 | + Column(Modifier.padding(16.dp)) { |
17 | 25 | val (state, dispatch) = useReducer<MyState, MyAction>(initialState) { state, action ->
|
18 |
| - when (action.type) { |
19 |
| - "increment" -> state.copy(count = state.count + 1) |
20 |
| - "decrement" -> state.copy(count = state.count - 1) |
21 |
| - else -> throw Error() |
| 26 | + when (action) { |
| 27 | + MyAction.Increment -> state.copy(count = state.count + 1) |
| 28 | + MyAction.Decrement -> state.copy(count = state.count - 1) |
22 | 29 | }
|
23 | 30 | }
|
24 | 31 |
|
25 | 32 | Text("Count: ${state.count}")
|
26 | 33 | Button(onClick = {
|
27 |
| - dispatch(MyAction("increment")) |
| 34 | + dispatch(MyAction.Increment) |
28 | 35 | }) {
|
29 | 36 | Text("+")
|
30 | 37 | }
|
31 | 38 | Button(onClick = {
|
32 |
| - dispatch(MyAction("decrement")) |
| 39 | + dispatch(MyAction.Decrement) |
33 | 40 | }) {
|
34 | 41 | Text("-")
|
35 | 42 | }
|
|
0 commit comments