carbaj0
05/05/2021, 5:45 AMcarbaj0
05/05/2021, 5:45 AMcarbaj0
05/05/2021, 5:45 AMsealed class State
object Error : State()
object Loading : State()
data class Success(
val tasks: Tasks,
val input: String,
) : State()
carbaj0
05/05/2021, 5:46 AMcarbaj0
05/05/2021, 5:46 AMcarbaj0
05/05/2021, 5:46 AMclass Store() : ViewModel() {
val state: MutableStateFlow<State> = MutableStateFlow(Loading)
fun Action.reduce(currentState: State): State =
when (this) {
is LoadTasks -> //copy of success state
is ChangeInput -> //copy of success - val input: String,
is AddTask -> //copy of success - val tasks: Tasks,
fun action(action: Action) {
state.value = action.reduce(state.value)
}
}
carbaj0
05/05/2021, 5:46 AMcarbaj0
05/05/2021, 5:49 AMsetContent {
val s by store.state.collectAsState()
when (val state = s) {
is Error -> Column {
Text(text = "Error")
Button(onClick = { store.action(LoadTasks) }) {
Text(text = "Reload")
}
}
is Loading -> Text(text = "Loading")
is Success ->
Column {
Log.e("render", "Column")
Row {
Log.e("render", "Row")
TextField(
value = state.input,
onValueChange = { store.action(ChangeInput(it)) }
)
Button(onClick = { store.action(AddTask(state.input)) }) {
Log.e("render", "Button")
Text(text = "Add")
}
Row {
Log.e("render", "Row2")
Row {
Log.e("render", "Row3")
}
}
}
LazyColumn {
items(state.tasks.tasks) { task ->
Text(text = task.task)
}
}
}
carbaj0
05/05/2021, 5:50 AMcarbaj0
05/05/2021, 5:50 AMcarbaj0
05/05/2021, 5:50 AMstate.input
dewildte
05/05/2021, 4:19 PMMutableState<String>
dewildte
05/05/2021, 4:20 PMdewildte
05/05/2021, 4:22 PMdewildte
05/05/2021, 4:25 PMdewildte
05/05/2021, 4:26 PMdewildte
05/05/2021, 4:29 PMcarbaj0
05/05/2021, 8:06 PMcarbaj0
05/05/2021, 8:07 PMcarbaj0
05/05/2021, 8:08 PMdewildte
05/05/2021, 9:00 PMcarbaj0
05/06/2021, 4:14 AMcarbaj0
05/06/2021, 4:15 AM