-1

I am trying to implement the following UI using ScrollableTabRow(), HorizontalPager(), and LazyColumn(), where LazyColumn will be available inside HorizontalPager as a pageContent.

enter image description here

So now the problem is when I swipe between pages of HorizontalPager or when I select any tab from the ScrollableTabRow, the pageContent (Text Composable in below code example) is called multiple times, and because of that, Composable LazyColum (which is my actual implementation) is called multiple times.

I am looking for a solution where the content of HorizontalPager can be loaded only once.

See below the code of HorizontalPager and check println() which explains the issue.

        HorizontalPager(
        pageCount = tabList.size, state = pagerState
    ) { page ->
        println("this line called multiple times when scrolled horizontally or any tab is selected")
        Text(text = "this is the text with page no. $page")
    }

Any help will be really appreciated.

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
  • I'm not sure if I understand the issue. Composable functions are expected to be called again every time the state of the UI changes. It's not building a fresh UI view hierarchy each time it's called--that's abstracted away and optimized out. – Tenfour04 Aug 08 '23 at 14:37
  • Alright, understood @Tenfour04 . Then how can I achieve above UI? Without compose I can use tablayout and viewpager2 from the XML, but I want to achieve the same using Compose. Let me know your thoughts on this. – Kishan Solanki Aug 08 '23 at 14:46
  • You already described a sensible way to build it above. – Tenfour04 Aug 08 '23 at 14:56
  • I take back what I said in the first comment. I haven't specifically used pagers before. It might be possible to optimize it to avoid the recompositions, which are not "free" performance-wise. That `tabList.size` property might be your issue, as it may not be considered "stable" by compose because collections are not provably immutable by the compiler. Assuming `tabList` doesn't actually change size, try putting it in a remembered variable -- `val tabListSize by remember { tabList.size }` and then use the variable as the argument for your HorizontalPager() call. – Tenfour04 Aug 09 '23 at 20:44
  • The above I think would solve it if the issue is just the collection size. But since I don't know pagers, I don't know if the `pagerState` is also unstable. But it probably is since it was built for Compose. – Tenfour04 Aug 09 '23 at 20:45

0 Answers0