android-jetpack-composekotlin-stateflowmutablestateof

combining multiple mutablestates


just started picking up Compose MP and have been running into difficulty combining 2 sources of mutablestates to a new mutablestate or flow within a viewmodel.

per documentation, I figured snapshotflow would be what I needed but it only seems to emit the initial value when viewmodel is initialized, while manipulations to v1 and v2 later do not emit further events.

I've attempted the following (v1, v2 are mutablestate objects)

in viewmodel

combinedFlow = snapshotFlow { v1 to v2 } 
    .mapLatest { (v1, v2) -> v1.value && v2.value } }
    .stateIn(viewmodelscope)

in composable

...
Button(...
        enabled = screenModel.combinedFlow.collectAsState(false).value,
...

what am I missing? If there are better practices for achieving this please say so, I remember something like transformations existed with livedata and combine for Rx.

thanks!


Solution

  • A day later..

    Wasted quite a bit of time over this, completely mislead by Google developer documentation..

    Seems like I wasn't the only one to fall down this rabbit hole.

    Why snapshotFlow is trigged with MutableState as property delegate?

    https://www.reddit.com/r/androiddev/comments/rqdv5g/there_are_three_ways_to_declare_a_mutablestate/

    Apparently reading the docs saying declarations of mutablestates have equivalent ways kept me from realizing this was the actual problem.

    in my ViewModel I didn't use the same declaration:

    var inputMessage by mutableStateOf("")
        private set
    

    as described in the example, but instead without the "by".

    Anyways, this led me to change the snapshot declaration to:

    snapshotFlow { v1.value to v2.value }
    

    And what do you know, magic.

    Hope one day developer docs will be written in a non ambiguous & simple way.