I have a HorizontalPager
(com.google.accompanist:accompanist-pager:0.20.0
) with two pages, each one containing a list of items. Each item has an enter animation that triggers on first composition. Upon composing the pager, both pages are also composed at the same time, but weirdly enough, not always.
I store PagerState
inside my view model for other reasons, so the last active tab is preserved. If it is the first page, both pages are composed simultaneously, causing a spike in frame time graph. However, if it is the second page, only it is composed with its list, and the first page is populated the instant I scroll in its direction. That's convenient!
Here's some pseudo code for better understanding.
@Composable
fun PagerScreen(viewModel: SomeViewModel) {
val firstList by viewModel.firstListFlow.collectAsState()
val secondList by viewModel.secondListFlow.collectAsState()
HorizontalPager(
state = viewModel.pagerState
/* ... */
) { index ->
// "Switch-case"ing tabs by index and displaying a LazyColumn for each.
}
}
If I navigate to this screen, scroll to the second tab, then navigate elsewhere and back again, the second tab will be composed without performance issues, and the first one will not be composed until I start to scroll to it, i.e. lazily. It actually looks like a bug, but I want this behavior in my case.
So the question is how do we force pager's pages to be composed lazily regardless?
It may be possible if we collect PagerState.targetPage
, but it requires nontrivial logic and I would like to avoid it since this behavior is already in place.
Update - some trippy stuff
The problem can be solved by adding any amount of itemSpacing
.
HorizontalPager(
state = viewModel.pagerState,
itemSpacing = 1.dp,
/* ... */
) { index ->
// "Switch-case"ing tabs by index and displaying a LazyColumn for each.
}
How? Why? We will never know. But doing this introduces another weird problem in a sibling library com.google.accompanist:accompanist-pager-indicators:0.20.0
, with indicator behaving improperly, as I demonstrate on this gif. Again, pay attention to the indicator.
As much as I love Compose, those little bugs here and there are driving me crazy.