Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does HorizontalPager's automatic scrolling stop after manual scrolling?

I have a HorizontalPager

val pageCount = bannerList.size
val startIndex = Int.MAX_VALUE / 2
val pagerState = rememberPagerState(initialPage = 100)
HorizontalPager(
    count = Int.MAX_VALUE,
    state = pagerState,
    contentPadding = PaddingValues(
        horizontal = 20.dp
    ),
    modifier = Modifier
        .fillMaxWidth()
) { index ->
// content goes here
}

and I made it scrolling every 4 second like banners with LaunchedEffect

LaunchedEffect(
    key1 = Unit,
    block = {
        repeat(
            times = Int.MAX_VALUE,
            action = {
                delay(
                    timeMillis = 4000
                )
                pagerState.animateScrollToPage(
                    page = pagerState.currentPage + 1
                )
            }
        )
    })

it scrolls fine every 4 second but when i scroll it manually HorizontalPager stops scrolling!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any suggestions how to fix this?

>Solution :

animateScrollToPage throws an exception when called during manual scrolling:

java.util.concurrent.CancellationException: Current mutation had a higher priority

You can solve it in many ways. For example just catch the exception and ignore it:

delay(
    timeMillis = 4000
)
try {
    pagerState.animateScrollToPage(
        page = pagerState.currentPage + 1
    )
} catch (_: Throwable) {
}

An other option is to check whether the pager is being dragged and stop your LaunchedEffect for this period of time:

val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
if (!isDragged) {
    LaunchedEffect(Unit) {
        // ...
    }
}

I think the second solution is cleaner, because in this case the timer will be restarted, and delay until the next scroll will always be the same.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading