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

1

19

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)
    }
}
Glutamate answered 6/8, 2020 at 13:35 Comment(1)
Here is the answer to your question: https://mcmap.net/q/554535/-how-to-show-empty-view-while-using-android-paging-3-libraryMacias
A
36

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
            }
           }
Accelerando answered 9/8, 2020 at 19:25 Comment(1)
Great solution! It works even better if you change it to if (loadState.source.refresh is LoadState.NotLoading && loadState.append.endOfPaginationReached) because then you can set the empty view back to invisible when a new search is triggeredTransfuse

© 2022 - 2024 — McMap. All rights reserved.