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 not sure if its proper condition
adapter.loadStateFlow.collectLatest { loadStates ->
viewBinding.sflLoadingView.setVisibility(loadStates.refresh is LoadState.Loading)
viewBinding.llErrorView.setVisibility(loadStates.refresh is LoadState.Error)
viewBinding.button.setOnClickListener { pagingAdapter.refresh() }
if(loadStates.refresh is LoadState.NotLoading && (viewBinding.recyclerView.adapter as ConcatAdapter).itemCount == 0){
viewBinding.llEmptyView.setVisibility(true)
}else{
viewBinding.llEmptyView.setVisibility(false)
}
}
Also I am running into other problem I have implemented search functionality and until more than 2 characters are entered i am using same paging source like following but the above loadstate callback is executed only once.So thats why i am not able to hide empty view if search query is cleared.I am doing so to save api call from front end.
private val originalList : LiveData<PagingData<ModelResponse>> = Transformations.switchMap(liveData){
repository.fetchSearchResults("").cachedIn(viewModelScope)
}
val list : LiveData<LiveData<PagingData<ModelResponse>>> = Transformations.switchMap{ query ->
if(query != null) {
if (query.length >= 2)
repository.fetchSearchResults(query)
else
originalList
}else
liveData { emptyList<ModelResponse>() }
}
repository.fetchSearchResults(query)
look like and when are you calling submitData? How are you verifying that the callback is only called once? You should be receiving a new CombinedLoadStates anytime any of the states change (including append / prepend). To be clear, your condition checks itemCount of ConcatAdapter, but I think you want itemCount of just the PagingDataAdapter, since ConcatAdapter will include other adapters (such as LoadStateAdapter) as well. FYI: You can usesubmitData(PagingData.empty())
to clear the list. – Weaklyfun fetchSearchResults(searchQuery : String): LiveData<PagingData<ModelResponse>> { return Pager( config = PagingConfig(pageSize = DEFAULT_PAGE_SIZE, enablePlaceholders = false), pagingSourceFactory = { ModelPagingSource(searchQuery) } ).liveData }
– GrasslandPagingSource
will cause issues. I would try to filter the search input instead so that you don't end up reloading when you don't want to instead of trying to "reuse" a PagingSource. For checking empty state,PagingDataAdapter.itemCount
will work when called from loadStateFlow / listeners (load state events are guaranteed to be sent synchronously with insert events, so you can be sure the loaded page has been presented). There is also a.snapshot()
method in case you need to view the actual items presented themselves. – Weakly