I'm using com.google.accompanist:accompanist-pager
to implement infinite scroll of pages. I implemented everything as described in HorizontalPagerLoopingSample
.
Everything works well, however, I need to track the change of the page, that is, on each scroll of the page, execute certain logic. For reacting to pages changes we can observe PagerState.currentPage
:
val pagerState = rememberPagerState()
LaunchedEffect(pagerState) {
// Collect from the pager state a snapshotFlow reading the currentPage
snapshotFlow { pagerState.currentPage }.collect { page ->
// some logic here
}
}
However, here I run into a problem, since we used count = Int.MAX_VALUE
to implement an infinite pager, then the page
is not actual page index.
I understand that we can recalculate the real page index, as we did for rendering the page by indeŃ…:
HorizontalPager(
// Set the raw page count to a really large number
count = Int.MAX_VALUE,
state = pagerState,
// Add 32.dp horizontal padding to 'center' the pages
contentPadding = PaddingValues(horizontal = 32.dp),
// Add some horizontal spacing between items
itemSpacing = 4.dp,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) { index ->
// We calculate the page from the given index
val page = (index - startIndex).floorMod(pageCount) // **THIS LINE TO CALCULATE REAL PAGE**
PagerSampleItem(
page = page,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
)
}
but in this case we are re-duplicating the code to get the real page index on page changed. Is it possible to do without it, and perform this calculation only once? Please help me figure it out.
Maybe someone managed to implement this, please share your advice.