blork
blork

Reputation: 2220

How to use Paging3 Library to start on the not-first page?

I'm trying to use PagingSource, LazyPagingItems and LazyColumn to display a dataset that extends into the past and the future.

I want the initial load of my list to be centered on "today", and allow the user to scroll up to go back in time, down to go forward in time. My paging source does this with a custom key, but the principle is the same as starting on the not-first page.

So for example, if my first page is 5, the first LoadResult.Page I return would look like this:

LoadResult.Page(
    data = list,
    prevKey = 4,
    nextKey = 6
)

If I do this, though, when the first page is loaded the LazyColumn immediately triggers the previous page load. I assume this is because after updating it is initially scrolled to the top, triggering the prev page load. This then continues to happen as more data is loaded and the list jumps to the new top over and over. This happens forever, loading every page in the past until there are no more.

How can I prevent the Column from jumping to the top when a previous page is loaded? Is Paging3 not suited to having a bi-directional set of data?

Upvotes: 2

Views: 1448

Answers (2)

Mohammad_Es0281
Mohammad_Es0281

Reputation: 1

The solution to this issue is to provide a key for the items in LazyColumn. Here, you can achieve this by using the itemKey function as shown below:

lazyPagingItems.itemKey { item -> item.key }

The problem arises because of the default behavior of LazyColumn, which identifies items solely by their index when no explicit key is provided. Consequently, when new items are inserted at the beginning of the list, such as when loading a previous page, the index of existing items changes. This results in LazyColumn automatically scrolling to a different item, often leading to infinite scrolling upwards.
For example, when you're currently viewing the item at index 3 and then the previous page is loaded, LazyColumn jumps to the new item that is placed at index 3 (scrolls up).

By assigning a key to each item, they are uniquely identified regardless of their position in the list. As a result, after loading a previous page, LazyColumn remains focused on the same item and prevents automatic scrolling up.

Upvotes: 0

blork
blork

Reputation: 2220

The solution was simply to provide keys for the items.

Without giving the items keys, they are identified solely by position, so the scroll state tries to keep the 0th item at the top. So we jump up forever.

I assumed that the items were identified through some other means by Compose, but no, just position.

Upvotes: 0

Related Questions