Issue
Basically I have a launched effect reading the item offset of a lazy column. and based on the offset I change the height/alpha etc..
AS is warning me that it should not be read inside a compose function because it will change a lot, so my question is where should I be reading and what is the best practice here? Should I make a lambda updating the offset outside of the function and read in the highest one? Or the parent one?
Open to suggestions
Solution
You can read it inside a derivedStateOf
.
val someData = remember {
derivedStateOf {
val offset = lazyListState.firstVisibleItemScrollOffset
val firstVisibleItem = lazyListState.firstVisibleItemIndex
// Convert to some data here and read this data
}
}
I did similar thing in this library for animating color, scale and alpha of items with
val animationData by remember {
derivedStateOf {
val animationData = getAnimationProgress(
lazyListState = lazyListState,
initialFirstVisibleIndex = initialFirstVisibleIndex,
indexOfSelector = indexOfSelector,
itemScaleRange = itemScaleRange,
showPartialItem = showPartialItem,
globalIndex = globalIndex,
selectedIndex = selectedIndex,
availableSpace = availableSpace,
itemSize = itemSizePx,
spaceBetweenItems = spaceBetweenItems,
visibleItemCount = visibleItemCount,
totalItemCount = totalItemCount,
inactiveScale = inactiveItemScale,
inactiveColor = inactiveColor,
activeColor = activeColor
)
selectedIndex = animationData.globalItemIndex
animationData
}
}
If you read a change you can read LaunchedEffect with snapshotFlow either but as i checked same lazyListState
is returned so it's not possible to read any change but you can read lazyListState.firstVisibleItemScrollOffset
or any changing value as alternative to derivedStateOf.
For instance
LaunchedEffect(Unit){
snapshotFlow { lazyListState.firstVisibleItemScrollOffset }
.onEach {
// Here we get the change in offset of first visible item
// You might read another value here and do calculation
lazyListState.firstVisibleItemIndex
}.launchIn(this)
}
I think reading lazyListState wouldn't pose any problems either. I use this when i only read one value like firstVisibleItemScrollOffset
, or layoutInfo inside snapshotFlow
Answered By - Thracian
Answer Checked By - Gilberto Lyons (JavaFixing Admin)