Hello, I am finding it hard to understand how does...
# compose
p
Hello, I am finding it hard to understand how does derivedStateOf decides that it needs to recalculate now? Bcz i have found it very hard to trigger on state updates. For ex:-
Copy code
val state: LazyListState = rememberLazyListState()

val stepSize by remember(totalSize) {
    mutableStateOf(
        when {
            (totalSize <= 100) -> TAB_THRESHOLD
            (totalSize <= 1000) -> TAB_THRESHOLD * 10
            else -> TAB_THRESHOLD * 50
        }
    )
}

//Why is this needed?
val rememberUpdatedStepSize by rememberUpdatedStepSize(stepSize)
val tabPosition by remember {
    derivedStateOf {
        state.firstVisibleItemIndex / rememberUpdatedStepSize
    }
}
In the above code “state.firstVisibleItemIndex” value is also a State but not only it updates the calculation on every change , it also takes the latest value The same can’t be said for “stepSize”,which can’t even trigger calculation not the correct value is fetched as it always takes initial value Only by using rememberUpdatedStepSize it works. Similar problem i found here as well https://kotlinlang.slack.com/archives/CJLTWPH7S/p1676315028809899
a
Actually
stepSize
never gets "updated", or we can say the way it's updated is wrong. You are creating a new
MutableState
instance whenever
totalSize
changes, instead of updating the value of the current
MutableState
instance.
derivedStateOf
will rerun the lambda when the any value of the states it captures change, but if you use
stepSize
directly, since the value of the initial
MutableState
instance remains unchanged, the lambda won't be rerun automatically.
p
Okay so from what I can see, if we are having a remember with a key, be careful to use it in these SideEffects APIs as it changes the reference of state itself. But what about method parameters ? Even changes in them seem to not trigger the calculation
a
Yeah because parameters are not states.
p
But how are they not state? If they were not state why would change in them update other comparables or even trigger remember when used as key.
Is it because they are part of some data class and what we pass down is just value, and on recomposition the entire tree is recreated so method parameters are nothing more than value?
a
You can use the value of a state as the parameter of a composable function at the call site, but inside the composable function being called, it's just a parameter.