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 🧵 👇
having such a function I would like to react on change, but have an access to new number and old one
Piotr Prus
10/01/2021, 9:38 AM
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") }
}
Piotr Prus
10/01/2021, 9:40 AM
I tried also with
snapshotFlow
, but the
lastValue
cannot be accessed from it
c
Csaba Kozák
10/01/2021, 12:01 PM
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
}
Csaba Kozák
10/01/2021, 12:10 PM
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
}
}