【问题标题】:How to clear adapter when new paging data is submitted?提交新的分页数据时如何清除适配器?
【发布时间】:2021-11-20 10:13:23
【问题描述】:

我有一个简单的分页搜索,可以在用户键入时查询服务器:

视图模型

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
}

Fragment 中,我观察此流并将其设置为 PagingDataAdapter:

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

现在,每当我触发新搜索时,我都会收到新的PagingData,然后我将其设置为适配器。 执行此操作后,CombinedLoadStates.refreshLoadState.Loading 但未清除适配器!

这意味着当我更改搜索时,适用于其他不更改内容的列表的以下加载处理会在旧数据之上显示 swipe2refresh 指示器,而不是全屏加载占位符(我的搜索也支持 swipe2refresh)查询:

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)

当提交新的分页数据以显示全屏加载占位符而不是 swipe2refresh 指示器时,是否有可能清除适配器数据?

【问题讨论】:

  • 发布您的DataSource

标签: android kotlin android-paging android-paging-library android-paging-3


【解决方案1】:

现在我决定在返回新的搜索流时始终发出 PagingData.empty()

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2019-07-09
    • 2012-12-02
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多