1

I have a simple paginated search that queries the server as the user types:

ViewModel:

private val searchTextStream = MutableStateFlow("")

val itemsStream: LiveData<PagingData<Item>> = searchTextStream
    .debounce(Duration.milliseconds(400))
    .flatMapLatest {
        val filter = ItemsFilter(name = it)
        getItemsStreamUseCase(filter)
    }
    .cachedIn(viewModelScope)
    .asLiveData()

fun search(text: String) {
    searchTextStream.value = text
}

In the Fragment I observe this stream and set it to a PagingDataAdapter:

viewModel.itemsStream.observeWithViewLifecycleOwner {
    adapter.submitData(viewLifecycleOwner.lifecycle, it)
}

Now, whenever I trigger a new search, I receive new PagingData which I then set to the adapter. Upon doing this, the CombinedLoadStates.refresh is LoadState.Loading but the adapter is not cleared!

Which means that the following loading handling, that works for other lists that don't change content, shows swipe2refresh indicator on top of old data instead of a full screen loading placeholder (my search also supports swipe2refresh) whenever I change the search query:

adapter.loadStateFlow
    .onEach {
        val showLoadingPlaceholder = it.refresh is LoadState.Loading && adapter.itemCount < 1
        val showSwipeRefreshIndicator = it.refresh is LoadState.Loading && adapter.itemCount > 0
        ...
        ...
    }
    .launchIn(viewLifecycleOwner.lifecycleScope)

Is there a possibility to clear the adapter data when new paging data is submitted to show a full screen loading placeholder instead of the swipe2refresh indicator?

mickp
  • 1,679
  • 7
  • 23

1 Answers1

0

For now I have decided to always emit PagingData.empty() whenever new search stream is being returned:

val itemsStream: LiveData<PagingData<Item>> = searchTextStream
    .debounce(Duration.milliseconds(400))
    .flatMapLatest {
        val filter = ItemsFilter(name = it)
        val stream = getItemsStreamUseCase(filter).cachedIn(viewModelScope)
        stream.onStart { emit(PagingData.empty()) }
    }
    .asLiveData()
mickp
  • 1,679
  • 7
  • 23