Jetpack compose infinity scroll listener

465 views Asked by At

I want to implement infinite scroll via LazyColumn in Jetpack Compose without any library. In other words I need a listener to be invoked when the user scrolls to the end.

1

There are 1 answers

3
beigirad On

I used this solution:

@Composable
inline fun LazyListState.scrollEndCallback(crossinline callback: () -> Unit) {
    LaunchedEffect(key1 = this) {
        snapshotFlow { layoutInfo }
            .filter { it.totalItemsCount > 0 }
            .map { it.totalItemsCount == (it.visibleItemsInfo.lastOrNull()?.index ?: -1).inc() }
            .distinctUntilChanged()
            .filter { it }
            .onEach { callback() }
            .collect()
    }
}

Its usage:

@Composable
fun Example() {
    LazyColumn(
        state = rememberLazyListState().also {
            it.scrollEndCallback {
                // do sth
            }
        },
    ) {
        // items ....
    }
}

Also it can be reused with LazyGridState