https://kotlinlang.org logo
#compose
Title
# compose
m

Marco Pierucci

02/23/2023, 2:48 PM
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

myanmarking

02/23/2023, 3:30 PM
drop(1) drops the first element. What is the problem ?
m

Marco Pierucci

02/23/2023, 3:38 PM
Am asking if doing this ok to prevent
onDaySelected
to be called due to the pager setting an initial value
m

myanmarking

02/23/2023, 3:40 PM
Cant you allow the initial value to go, and do your logic of skipping in the viewModel ?
your solution is correct, yes
m

Marco Pierucci

02/23/2023, 3:49 PM
Excellent, thanks!
22 Views