https://kotlinlang.org logo
#compose-android
Title
# compose-android
f

Fabio Berta

11/29/2023, 2:27 PM
Hi, I have a
HorizontalPager
and and I'd like to scroll to a certain page when a specific event happens. Unfortunately, I cannot hoist the pager state to a place where I have access to an event handler where I could perform the scroll. The way I can observe the event is comparing a parameter to a composable to the one from the previous composition. I came up with the following solution:
Copy code
@Composable
fun Something(parameter: SomeInterface) {
    val pagerState = rememberPagerState(
        initialPage = 0,
        pageCount = { 10 },
    )
    val previous = rememberPrevious(parameter)
    val isPreviousSome = previous is SomeInterface.SomeVariant
    val isCurrentSome = parameter is SomeInterface.SomeVariant
    if (!isPreviousSome && isCurrentSome) {
        val scope = rememberCoroutineScope()
        SideEffect {
            scope.launch { pagerState.animateScrollToPage(1) }
        }
    }
}

sealed interface SomeInterface {
    data object SomeVariant: SomeInterface
    data object OtherVariant: SomeInterface
}

@Composable
fun <T> rememberPrevious(currentValue: T): T {
    var value by remember { mutableStateOf(currentValue) }

    SideEffect {
        value = currentValue
    }

    return value
}
It works but it somehow feels a bit off to me. Maybe I'm doing something wrong in the first place?
I actually ended up transforming
parameter
into a state using
rememberUpdatedState
and then subscribing to it in a
LaunchedEffect
using
snapshotFlow
. This allows me to easily detect the change I'm interested in using
runningFold
. All in all, this feels better.