https://kotlinlang.org logo
#compose
Title
# compose
t

than_

03/08/2021, 3:41 PM
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

Zach Klippenstein (he/him) [MOD]

03/08/2021, 4:50 PM
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

than_

03/08/2021, 5:10 PM
Yes, that's the case. Should have been clearer, sorry.
z

Zach Klippenstein (he/him) [MOD]

03/08/2021, 5:32 PM
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

than_

03/08/2021, 6:49 PM
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

Zach Klippenstein (he/him) [MOD]

03/08/2021, 7:06 PM
are you `remember`ing that?
t

than_

03/08/2021, 7:59 PM
sure, call site looks like this:
Copy code
val (stt, dispatch) = remember { reducerStateOf(1, ::reducer) }
z

Zach Klippenstein (he/him) [MOD]

03/08/2021, 8:09 PM
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

than_

03/08/2021, 9:21 PM
Yep that was it 🙂 thank you very much
👍 1
3 Views