Jetpack Compose HorizontalPager Page Change Callback

May 6, 2022
fun PhotoPagerScreen(
    images: List<Image>,
    page: Int,
    onPageChange: (Int) -> Unit
) {

    val pagerState = rememberPagerState()

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.collect { page ->
            onPageChange(page)
        }
    }

    HorizontalPager(count = images.size, state = pagerState) { page ->
        // load composable
    }

    LaunchedEffect(page) {
        pagerState.scrollToPage(page)
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.