onPageSelected callback for JetPack Compose Pager

Viewed 2914

I am using JetPack Compose Pager from Accompanist and I'm wonder how do I know exactly when my page is Showed at screen. Like onPageSelected method from ViewPager.

Here is my code:

HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.background)
    ) { page ->
         // This method reinvoked many times.

      }

'Cause currently each recomposition would invoke that callback method from Pager.

5 Answers

I think it will be better to use

LaunchedEffect(pagerState) {
    snapshotFlow { pagerState.currentPage }.collect { page ->
        // do your stuff with selected page
    }
}

To complete @ysfcyln solution here is the official documentation :

https://google.github.io/accompanist/pager/#reacting-to-page-changes

the full example there is :

val pagerState = rememberPagerState()

LaunchedEffect(pagerState) {
    // Collect from the a snapshotFlow reading the currentPage
    snapshotFlow { pagerState.currentPage }.collect { page ->
        AnalyticsService.sendPageSelectedEvent(page)
    }
}

VerticalPager(
    count = 10,
    state = pagerState,
) { page ->
    Text(text = "Page: $page")
}

Use a variable to keep track

val trigger by remember { mutableStateOf (false) }
HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.background)
    ) { page ->
         // Shown successfully,
         trigger = true //use at other places as a callback to change state
      }

We can do our tasks without any callbacks using PagerState.

val pagerState = rememberPagerState(pageCount = list.size)
        
        HorizontalPager(state = pagerState) { page ->
            // Our page content
            CardItemView(page, list[page])
        }

// Do your tasks based on the current page selected using pagerState.currentPage
        Toast.makeText(
            LocalContext.current,
            "Page selected ${pagerState.currentPage}",
            Toast.LENGTH_SHORT
        ).show()

This is a solution simpler than the one from the official documentation

LaunchedEffect(pagerState.currentPage) {
        // do your stuff with pagerState.currentPage
}
Related