I’m creating an infinite scroll in Jetpack Compose
. Given the LazyRow
:
LazyRow(
contentPadding = PaddingValues(start = 10.dp, end = 10.dp, bottom = 10.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
items (
lastIndexToShow,
key = { index ->
games.getOrNull(index)?.id ?: index
}
) { index ->
Box {
games.getOrNull(index)?.let { game ->
GameCard(game = game, index = index)
} ?:
Box(modifier = Modifier
.size(width = 400.dp, height = 350.dp)
.padding(0.dp))
}
LaunchedEffect(Unit) {
fetchNewPageIfNeeded(section, index)
}
}
}
}
games
and lastIndexToShow
come both from my ViewModel
. The idea of lastIndexToShow
is to allow showing empty spaces while loading in case of fast scrolling, so that the scroll never stops when hitting the end of games list before loading. And this is exactly the variable that ain’t working fine.
Here’s how I defined them:
games
private var _games = mutableStateMapOf<String, MutableList<Game>>()
val games: SnapshotStateMap<String, MutableList<Game>> = _games
lastIndexToShow
val lastIndexToShow: (String) -> State<Int> = { section ->
derivedStateOf {
maxOf(0, minOf((totalGamesGroupBy?.get(section) ?: 1) - 1, (_games[section] ?: emptyList()).size + threshold))
}
}
then I pass lastIndexToShow
like this.-
lastIndexToShow = { section ->
val indexToShow by gameViewModel.lastIndexToShow(section)
indexToShow
}
If instead of this variable I just set 1000
for the last index to show (I’m fetching 30 elements pages) I can see the row showing the new elements smoothly, so I’m pretty sure the issue is with the definition.
Been struggling for a while as still not very familiar with the recomposition flow. Any idea pointing in the right direction would be much appreciated 🙂