Can I get better alternatives for detecting the sc...
# compose
r
Can I get better alternatives for detecting the scroll direction in a
LazyColumn
. Here is what I have but it looks too hacky to me even though it works really well. Code in thread....
Copy code
/**
 *  A [LazyColumn] which reports if the items are being scrolled up or down
 *
 * @param modifier
 * @param state
 * @param contentPadding
 * @param reverseLayout
 * @param verticalArrangement
 * @param horizontalAlignment
 * @param flingBehavior
 * @param onScrollUp Fired when the items are scrolled up
 * @param onScrollDown Fired when the items are scrolled down
 * @param content
 */
@Suppress("UNUSED_VALUE")
@Composable
fun ObservableLazyColumn(
    modifier: Modifier = Modifier,
    state: LazyListState = rememberLazyListState(),
    contentPadding: PaddingValues = PaddingValues(0.dp),
    reverseLayout: Boolean = false,
    verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(10.dp),
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
    onScrollUp: () -> Unit,
    onScrollDown: () -> Unit,
    content: LazyListScope.() -> Unit
) {
    var firstVisibleItem by remember { mutableStateOf(state.firstVisibleItemIndex) }

    if (firstVisibleItem > state.firstVisibleItemIndex) {
        onScrollDown()
    } else if (firstVisibleItem < state.firstVisibleItemIndex) {
        onScrollUp()
    }

    firstVisibleItem = state.firstVisibleItemIndex

    LazyColumn(
        modifier = modifier,
        state = state,
        contentPadding = contentPadding,
        flingBehavior = flingBehavior,
        horizontalAlignment = horizontalAlignment,
        verticalArrangement = verticalArrangement,
        reverseLayout = reverseLayout,
        content = content
    )
}
a
You can use nested scroll mechanism.
Copy code
val nestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            if (available.y > 0) {
                // Scrolling down
            } else {
                // Scrolling up
            }
            return Offset.Zero
        }
    }
}
LazyColumn(modifier = Modifier.nestedScroll(nestedScrollConnection)) {
    // Items
}
3
d
IDE is failing when trying to use
NestedScrollConnection
from Compose/MP - does anyone know if it should be available from that Compose version?
a
It's available since the end of last year I guess.