Home > Enterprise >  Why does HorizontalPager's automatic scrolling stop after manual scrolling?
Why does HorizontalPager's automatic scrolling stop after manual scrolling?

Time:03-29

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!

any suggestions how to fix this?

CodePudding user response:

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.

  • Related