Hi, I'm trying to update my state with reducer. Th...
# compose
t
Hi, I'm trying to update my state with reducer. The only way I was able to achieve that was by using
ViewModel
and
collectAsState
but by doing that I lost the ability to change state in the interactive mode in android studio. Is there something I'm missing?
z
Not quite sure what you’re seeing - when running your compose preview in interactive mode, updates to your view model State are not triggering recomposition?
t
Yes, that's the case. Should have been clearer, sorry.
z
I’m very much just guessing here, but since the interactive preview isn’t running a real environment, it might be doing something weird with the view model provider - maybe the fake provider isn’t memoizing correctly or something?
t
Yeah seems like it. I've tried to make it work without ViewModel using something like this
that does not update the state at all 😕
z
are you `remember`ing that?
t
sure, call site looks like this:
Copy code
val (stt, dispatch) = remember { reducerStateOf(1, ::reducer) }
z
Wouldn’t you want to return a
State<STATE>
in that pair? Right now you’re just returning the initial state value as the raw value, which means it has no way to be updated after being memoized by
remember
so e.g.
Copy code
fun <ACTION, STATE> reducerStateOf(initialValue: STATE, reducer: Reducer<ACTION, STATE>): Pair<State<STATE>, Dispatch<ACTION>> {
    val state = mutableStateOf(initialValue)

    val dispatch: Dispatch<ACTION> = {action: ACTION ->
        val newState = reducer(action, state.value)
        state.value = newState
    }

    return state to dispatch
}
i’m guessing that’s why you’re not seeing changes
t
Yep that was it 🙂 thank you very much
👍 1