3

I am using the Paging library from Android Jetpack to have a paged loading behavior in my RecyclerView. Now I want a simple thing - get a signal in my UI that there is no data and the list is empty, so that I can show a message like "there are no items".

The problem is that I'm using PositionalDataSource without placeholders since I have no idea how big the list will be. Another problem is that I can only take the loaded items from the PagedList so I have no idea if more data is being currently loaded from my DataSource.

So the question is - does the PagedList or DataSource give out a signal like "i'm done loading"? That event is clearly defined in the library, since it will stop loading once it gets less data than asked, as mentioned here: Returned data must be of this size, unless at end of the list. The question is - can I get that event signaled to me somehow?

For now I see the following solution. I have implemented my DataSource.Factory just like in the Android Guide shows in this page: giving out my DataSource as a LiveData in factory. Besides, I already exposed a LiveData object from DataSource called isLoading, I use it in the UI to show a progress bar every time DataSource loads something. I'm thinking to add another LiveData called emptyResults and then I can wire both together in my UI so that I will show my "no items" message when emptyResults && !isLoading.

I wonder if there is a better way to do this.

frangulyan
  • 3,580
  • 4
  • 36
  • 64

1 Answers1

3

This solution worked for me:

Add an adapter observer:

adapter?.registerAdapterDataObserver(adapterObserver)

Detect if the list is empty and 0 items are inserted

private val adapterObserver = object : RecyclerView.AdapterDataObserver() {
    override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {

        val count = adapter?.itemCount
        if (itemCount == 0 && count == 0) {
            // List is empty
        } else {
            // List is not empty
        }
    }
}
svprdga
  • 2,171
  • 1
  • 28
  • 51