Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save manavtamboli/567a76a391203dea14b714b52b708432 to your computer and use it in GitHub Desktop.

Select an option

Save manavtamboli/567a76a391203dea14b714b52b708432 to your computer and use it in GitHub Desktop.
@Composable
fun MyContent(listItems : List<Data>){
val listState = rememberLazyListState()
LazyColumn(state = listState){
items(listItems){
// ...
}
}
// This will start loading more when reaches at total - 2 items
listState.OnBottomReached(buffer = 2) {
viewModel.fetchMoreItems()
}
}
@Composable
fun LazyListState.OnBottomReached(
// tells how many items before we reach the bottom of the list
// to call onLoadMore function
buffer : Int = 0,
onLoadMore : () -> Unit
) {
// Buffer must be positive.
// Or our list will never reach the bottom.
require(buffer >= 0) { "buffer cannot be negative, but was $buffer" }
val shouldLoadMore = remember {
derivedStateOf {
val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
?:
return@derivedStateOf true
// subtract buffer from the total items
lastVisibleItem.index >= layoutInfo.totalItemsCount - 1 - buffer
}
}
LaunchedEffect(shouldLoadMore){
snapshotFlow { shouldLoadMore.value }
.collect { if (it) onLoadMore() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment