'How to verify state change in Compose?

Say in a composable I have two states:

var stateA by remember { mutableStateOf(varA) }
var stateB by remember { mutableStateOf(varB) }

varA and varB are class variables of type Int and are set elsewhere in the code.

Then somewhere in the composable, in the same scope, I have

processA(stateA)
processB(stateB)

processA and processB are not composable functions.

So after initial rendering, if neither state changes, then nothing is further processed, that is cool.

Then if say stateB is changed, then both process statements get called. But I hope only to call processB in the case and not processA. How can I detect which of the states has changed?



Solution 1:[1]

You should not run heavy processing directly from Composable functions. More information can be found in side effects documentation.

In this case, you can use LaunchedEffect. Using snapshotFlow, you can create a flow that emits values every time a state changes, so you can process it. You can have a flow for each state, so they will be processed independently.

LaunchedEffect(Unit) {
    launch {
        snapshotFlow { stateA }
            .collect(::processA)
    }
    launch {
        snapshotFlow { stateB }
            .collect(::processB)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pylyp Dukhov