Hello! It's dropping the first element of the page...
# compose
m
Hello! It's dropping the first element of the pager
snapshotFlow
Copy code
LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.drop(1).collect { page ->
            onDaySelected(dates[page])
        }
    }
The correct approach for preventing a pageSelected callback to be called if the pager sets an initial page?
Full snippet:
Copy code
@OptIn(ExperimentalPagerApi::class)
@Composable
fun DayPicker(
    modifier: Modifier = Modifier,
    startDate: LocalDate,
    endDate: LocalDate,
    initialDate: LocalDate,
    contentPadding: PaddingValues = PaddingValues(0.dp),
    textStyle: TextStyle = MaterialTheme.typography.h5,
    onDaySelected: (LocalDate) -> Unit
) {
    val dates = remember(startDate, endDate) {
        (0..ChronoUnit.DAYS.between(startDate, endDate)).map {
            startDate.plusDays(it)
        }
    }

    val sanitizedInitialDate = remember(initialDate) {
        if (initialDate.isAfter(startDate) && initialDate.isBefore(endDate)) initialDate else startDate
    }
    val pagerState = rememberPagerState(initialPage = dates.indexOf(sanitizedInitialDate))

    VerticalPager(
        modifier = modifier,
        state = pagerState,
        count = dates.size,
        contentPadding = contentPadding,
        key = { page -> dates[page] }
    ) { page ->
        val pageDate = dates[page]
        Text(
            modifier = Modifier.graphicsLayer {
                val pageOffset =
                    calculateCurrentOffsetForPage(page).absoluteValue
                lerp(
                    start = 0.80f,
                    stop = 1f,
                    fraction = 1f - pageOffset.coerceIn(0f, 1f)
                ).also { scale ->
                    scaleX = scale
                    scaleY = scale
                }
                alpha = lerp(
                    start = 0.5f,
                    stop = 1f,
                    fraction = 1f - pageOffset.coerceIn(0f, 1f)
                )
            },

            text = pageDate.format(DateTimeFormatter.ofPattern("MMM dd")),
            style = textStyle
        )
    }

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.drop(1).collect { page ->
            onDaySelected(dates[page])
        }
    }
}
m
drop(1) drops the first element. What is the problem ?
m
Am asking if doing this ok to prevent
onDaySelected
to be called due to the pager setting an initial value
m
Cant you allow the initial value to go, and do your logic of skipping in the viewModel ?
your solution is correct, yes
m
Excellent, thanks!