Infinite scrolling using pagination API calls in Jetpack Compose

Infinite scrolling using pagination API calls in Jetpack Compose

effect
Recently, I added an infinite scroll with paging API calls to DashCoin's coin screen. It made it very difficult to browse the coin list, and it did reduce the initial load time, much less than before. Implementing infinite scrolling can be tricky if not implemented correctly. It can easily trigger recompression and cause infinite API calls. Here's how I implement it:

Set up pagination API calls and handle UI state

Your API call should have three states. load, success, error

In loading state :
you want to update your screen with loading state
wow
in success state :

  • Set your Loading status back to false.
  • Append the new list from the response to the old list.
  • Set the new pagination key.
  • You want to determine if the response returns an empty list, which means you reached the end of the file, which means you don't need to continue sending requests to the server.
    screenState
    error state :
  • Set your loading state back to false
  • update your error value

screenState

Paging data processing

Now that we have handled the screen state, we can create the Infinite Scroll Handler Composable :
it takes a,

  • Lazy list state to know about list properties
  • buffer and a callback function to load more items
  • Any
    state that requires computation and may trigger a reorganization should be remembered as a derived state.

See here we get total item count and last item index from lazy list state and compare if last item visible index is greater than total item count minus buffer which means we reached the end of the list.

Now we start on our remembered state LaunchedEffectand SnapshotFlowcollect state values ​​via to trigger our callback function.

infiniteState
If your listing loads instantly, make sure to :

  • Make sure you have two separate functions, getItemsFirstLoad() and getItemsPaginated().
  • The first load will call getItemsFirstLoad() and check if the list of items is empty on first load.
  • getItemsPaginated() is called every time you scroll to the end of the list to load more items, it checks that you have not reached the end of the responsive list and the list is not empty.

list implementation
Now your list should look like this
infinite scroll effect

Project source code

Project reference address:

https://github.com/MathRoda/DashCoin

Guess you like

Origin blog.csdn.net/u011897062/article/details/130344427