Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the list is empty on the first request in Paging 3.0

I'm trying to check if the first request came with the empty object, to display a layout indicating that it has no item.

My solution was to create an exception of my own. I would like to know if there is another better way. Because I looked in the documentation and found nothing.

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
    return try {
        val position = params.key ?: FIRST_PAGE_INDEX
        val response = api.getItem(position, params.loadSize, searchKey)
        val nextKey = response?.next
        val itemList = response?.itemList ?: emptyList()

        if (itemList.isNotEmpty()) {
            LoadResult.Page(
                data = itemList,
                prevKey = null,
                nextKey = if (nextKey == LAST_PAGE_INDEX) null else nextKey
            )
        } else {
            LoadResult.Error(EmptyListException())
        }

    } catch (exception: IOException) {
        LoadResult.Error(exception)
    } catch (exception: HttpException) {
        LoadResult.Error(exception)
    }
}
like image 562
OliverDamon Avatar asked Aug 06 '20 13:08

OliverDamon


People also ask

What is PagingSource in Android?

An instance of a PagingSource is used to load pages of data for an instance of PagingData . A PagingData can grow as it loads more data, but the data loaded cannot be updated. If the underlying data set is modified, a new PagingSource / PagingData pair must be created to represent an updated snapshot of the data.

How do I refresh pagination?

Go to the MainActivity layout file, activity_main. xml and add the SwipeRefreshLayout . You'll have a RecyclerView layout that we're using to handle the pagination. This RecyclerView now needs to be wrapped with a SwipeRefreshLayout .

What is Library pagination?

The Paging Library lets you load data directly from your backend using keys that the network provides. Your data can be uncountably large. Using the Paging Library, you can load data into pages until there isn't any data remaining. You can observe your data more easily.


1 Answers

To show EmptyView you can look loadState.append which represents the load state for loading data at the end of the list and can confirm if there is no more data to load using endOfPaginationReached and after that can check itemCout of PagingDataAdapter. ` .

eg:  adapter.addLoadStateListener { loadState ->

            if ( loadState.append.endOfPaginationReached )
            {
               if ( adapter.itemCount < 1)
                    /// show empty view
               else 
                   ///  hide empty view
            }
           }
like image 200
Saraju Pradhan Avatar answered Oct 31 '22 07:10

Saraju Pradhan