Hello community. I am trying to find a way to make...
# compose
p
Hello community. I am trying to find a way to make stateful composable that knows new and previous state upon the change. I would like to make an action that takes old value as parameter when the new value comes. Is taht possible using some sideEffect? I tried, but with no luck so far. More in 🧵 👇
Copy code
@Composable
fun MyComposable() {
var myNumber: Int? = remember { mutableStateOf(null) }
Text(text = "$myNumber")
Button(onCLick = { myNumber = Random.nextInt(0, 100) }) { Text("Click me") }
}
having such a function I would like to react on change, but have an access to new number and old one
Copy code
@Composable
fun MyComposable() {
var myNumber: Int? = remember { mutableStateOf(null) }
LaunchedEffect(myNumber) {
  // I tried to access the previous value from here, but I didnt find it :( 
}
Text(text = "$myNumber")
Button(onCLick = { myNumber = 2 }) { Text("Click me") }
}
I tried also with
snapshotFlow
, but the
lastValue
cannot be accessed from it
c
You can do something like this:
Copy code
var previousNumber by remember {
            mutableStateOf(0)
        }

        var currentNumberNumber by remember {
            mutableStateOf(0)
        }

        Button(onClick = {
            previousNumber = currentNumberNumber
            currentNumberNumber++
        }) {
            Text(text = "click me")
        }
        
        LaunchedEffect(previousNumber, currentNumberNumber) {
            // action based on previous and current
        }
snapshotFlow
could also help:
Copy code
LaunchedEffect(currentNumberNumber) {
            snapshotFlow {
                currentNumberNumber
            }.scan(0 to 0) { accumulator, value ->
                accumulator.second to value
            }.collect {
                val previousValue = it.first
                // action
            }
        }
p
thanks. I did 2 remember values and its working 🙂
👍 1