LilMoke
LilMoke

Reputation: 3454

Jetpack Compose Horizontal Pager Swipe Delay

I have a Jetpack Compose App that uses a Horizontal Pager. The behavior I am seeing is that when I swipe to my next page it moves smooth, but when I swipe back the screen advances about 3/4 of the way and pauses and then if I wait it completes the swipe.

Question:

Is this normal and controlled by the Fling Behavior?

Or could it be my implementation?

Has anyone else experienced this?

Upvotes: 1

Views: 5102

Answers (2)

Inidam Leader
Inidam Leader

Reputation: 649

There is a trick to solve this issue:

You have to use the beyondBoundsPageCount parameter set to 1 to load the two adjacent page contents, and observe settled page to start loading upcoming content only when you stop scrolling (which means: the current page is settled).

The default pager behavior is to start loading the content of adjacent pages at the beginning of scroll -even by 1px- and that makes your scroll janky because of entering composition that blocks main thread.

I’ve put more explanation on this issuetracker

val pagerState = rememberPagerState(initialPage = initialPage) { items.size }
val beyondBoundsPageCount = 1
HorizontalPager(
    modifier = modifier,
    state = pagerState,
    beyondBoundsPageCount = beyondBoundsPageCount,
    key = { items[it].id },
) { page ->
    @Suppress("NAME_SHADOWING")
    val page by rememberUpdatedState(newValue = page)

    var showContent by remember { mutableStateOf(false) }
    LaunchedEffect(key1 = Unit) {
        snapshotFlow { Pair(pagerState.isScrollInProgress, abs(pagerState.settledPage - page)) }.collectLatest { (scrollInProgress, diff) ->
            if (!scrollInProgress && (diff in 0..beyondBoundsPageCount)) {
                if (diff > 0) delay(1000)
                showContent = true
                cancel()
            }
        }
    }

    if (showContent) {
        // Content
    } else {
        CircularProgressIndicator()
    }
}

Upvotes: 0

WitWicky
WitWicky

Reputation: 291

It depends on the content in horizontal pager.When I use a simple coil image, it works fine.But when I have vertical pager/lazy column inside a horizontal pager, it lags. Also mentioned here: How to optimise laggy JetPack Compose layout

Upvotes: 1

Related Questions