Piotr Prus

    Piotr Prus

    11 months ago
    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 🧵 👇
    @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
    @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
    Csaba Kozák

    Csaba Kozák

    11 months ago
    You can do something like this:
    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:
    LaunchedEffect(currentNumberNumber) {
                snapshotFlow {
                    currentNumberNumber
                }.scan(0 to 0) { accumulator, value ->
                    accumulator.second to value
                }.collect {
                    val previousValue = it.first
                    // action
                }
            }
    Piotr Prus

    Piotr Prus

    11 months ago
    thanks. I did 2 remember values and its working 🙂