如何检查 Paging 3 库中的列表大小或空列表

How to check the list size or for empty list in Paging 3 library

我已经按照此处提供的说明成功实施了 Paging 3 库的新 alpha07 版本:https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#guava-livedata

但是,现在我需要检查 returned 列表是否为空以便向用户显示视图或文本,但我无法在其中附加任何检查他们分页设计的流程结构。

目前,在遵循他们的指南后,我的 Java 中的代码是这样的:

        MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);

        LifecycleOwner lifecycleOwner = getViewLifecycleOwner();
        Lifecycle lifecycle = lifecycleOwner.getLifecycle();
        Pager<Integer, MyEntity> pager = new Pager<>(new PagingConfig(10), () -> viewModel.getMyPagingSource());
        LiveData<PagingData<MyEntity>> pagingDataLiveData = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), lifecycle);

        pagingDataLiveData.observe(lifecycleOwner, data -> adapter.submitData(lifecycle, data));

我尝试在 adapter.submitData(lifecycle, data) 中的 data 上附加 .filter,但它从未收到 null 项,尽管列表为空。

在这种情况下,如何检查提交给适配器的数据何时为空?我在他们的文档中找不到任何指示。

编辑:这是我找到的解决方案,张贴在这里是因为选择的答案严格来说不是解决方案,也不在 java 中,而是引导我找到它的答案。

我必须附上一个 LoadStateListener to my adapter, listen for when the LoadType is REFRESH and the LoadStateNotLoading,然后检查 adapter.getItemCount 是否是 0。

可能不同的 LoadType 更适合这种情况,但到目前为止刷新对我来说是有效的,所以我选择了那个。

示例:

// somewhere when you initialize your adapter
...
myAdapter.addLoadStateListener(this::loadStateListener);
...
private Unit loadStateListener(@Nonnull CombinedLoadStates combinedLoadStates) {

    if (!(combinedLoadStates.getRefresh() instanceof LoadState.NotLoading)) {
        return Unit.INSTANCE; // this is the void equivalent in kotlin
    }

    myView.setVisibility(adapter.getItemCount() == 0 ? View.VISIBLE : View.INVISIBLE);

    return Unit.INSTANCE; // this is the void equivalent in kotlin

}

注意:我们必须 return Unit.INSTANCE 因为该侦听器在 kotlin 中并且该代码正在 java 中使用,returning 这相当于没有 returning java 中的任何内容(无效)。

PagingData 运算符对单个项目进行运算,因此如果页面为空则不会触发它们。

相反,您想在页面加载后通过观察 loadStateFlow 检查 PagingDataAdapter.itemCount。

loadStateFlow.map { it.refresh }
    .distinctUntilChanged()
    .collect {
        if (it is NotLoading) {
            // PagingDataAdapter.itemCount here
        }
    }

顺便说一句,null是Paging中的一个特殊值,表示占位符,所以你不应该给包含nulls的Paging页面,这就是为什么[=13=的下界] 泛型是 non-null Any 而不是 Any?

不幸的是,接受的答案对我的情况并不适用。 因此,当 api returns 空列表(按设计它不应该)时,我没有检查适配器的 itemCount 抛出自定义异常(我们称之为 EmptyListException)。在我的 PagingSource.load() 方法中,我检查获取的数据是否为空:

return if (pagedResponse.page.isEmpty()){
    LoadResult.Error(EmptyListException())
} else {
    LoadResult.Page(pagedResponse.page, prevKey, nextKey)
}

然后我在 adapter.loadStateFlow 中处理结果。