Last active
January 14, 2024 05:02
-
-
Save manavtamboli/567a76a391203dea14b714b52b708432 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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() | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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