I want to show empty view when paging3 is loaded with an empty list.
It seems to work with following code. Is this the proper way to do with the paging 3 library?:
adapter?.addLoadStateListener { loadState -> adapter?.apply { if (itemCount <= 0 && !loadState.source.refresh.endOfPaginationReached) { Timber.d("==> to show empty view") tvEmptyView.isGone = false } else { Timber.d("==> to hide empty view") tvEmptyView.isGone = true } } }
Answer
You can directly plug into the adapter loadStateFlow, e.g
lifecycleScope.launchWhenCreated { @OptIn(ExperimentalCoroutinesApi::class) adapter.loadStateFlow.collectLatest { loadStates -> val refresher = loadStates.refresh val displayEmptyMessage = (refresher is LoadState.NotLoading && refresher.endOfPaginationReached && adapter.itemCount == 0) layoutBinding.emptyStateMessage.isVisible = displayEmptyMessage layoutBinding.emptyStateImage.isVisible = displayEmptyMessage layoutBinding.swipeToRefresh.isRefreshing = refresher is LoadState.Loading } }