Prateek Kumar
07/28/2023, 2:23 AMval 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/p1676315028809899Albert Chang
07/28/2023, 5:18 AMstepSize
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.Prateek Kumar
07/28/2023, 5:36 AMAlbert Chang
07/28/2023, 8:09 AMPrateek Kumar
07/28/2023, 11:09 AMPrateek Kumar
07/28/2023, 11:11 AMAlbert Chang
07/28/2023, 6:04 PM