Skip to content Skip to sidebar Skip to footer

How To Show Empty View While Using Android Paging 3 Library

I am using Paging 3 lib. and i am able to check if refresh state is 'Loading' or 'Error' but i am not sure how to check 'empty' state.I am able to add following condition but i am

Solution 1:

Here is the proper way of handling the empty view in Android Paging 3:

adapter.addLoadStateListener { loadState ->
            if (loadState.source.refresh is LoadState.NotLoading && loadState.append.endOfPaginationReached && adapter.itemCount < 1) {
                recycleView?.isVisible = false
                emptyView?.isVisible = true
            } else {
                recycleView?.isVisible = true
                emptyView?.isVisible = false
            }
        }

Solution 2:

I am using this way and it works.

EDITED: dataRefreshFlow is deprecated in Version 3.0.0-alpha10, we should use loadStateFlow now.

  viewLifecycleOwner.lifecycleScope.launch {
            transactionAdapter.loadStateFlow
                .collectLatest {
                    if(it.refresh is LoadState.NotLoading){
                        binding.textNoTransaction.isVisible = transactionAdapter.itemCount<1
                    }
                }
        }

For detailed explanation and usage of loadStateFlow, please check https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#load-state-listener

Solution 3:

adapter.loadStateFlow.collect {
    if (it.append is LoadState.NotLoading && it.append.endOfPaginationReached) {
        emptyState.isVisible = adapter.itemCount < 1
    }
}

The logic is,If the append has finished (it.append is LoadState.NotLoading && it.append.endOfPaginationReached == true), and our adapter items count is zero (adapter.itemCount < 1), means there is nothing to show, so we show the empty state.

PS: for initial loading you can find out more at this answer: https://stackoverflow.com/a/67661269/2472350

Post a Comment for "How To Show Empty View While Using Android Paging 3 Library"