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

标签 android android-paging android-paging-library

按照此处提供的说明,我已经能够成功实现新的 alpha07 版本的 Paging 3 库:https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#guava-livedata
但是,现在我需要检查返回的列表是否为空,以便向用户显示 View 或文本,但我无法在他们的分页设计的流程结构中附加任何检查。
目前,这就是我在我的 onViewCreated 中使用 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));
我尝试附加一个 .filter在我的 dataadapter.submitData(lifecycle, data) ,但它从未收到 null尽管列表为空,但项目。
在这种情况下如何检查提交给适配器的数据何时为空?我在他们的文档中找不到任何指针。
编辑:这是我找到的解决方案,在这里发布是因为选择的答案不是严格意义上的解决方案,也不是 java 中的解决方案,而是引导我找到它的答案。
我必须附上 LoadStateListener到我的适配器,听LoadTypeREFRESHLoadStateNotLoading ,然后检查 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

}
注意:我们必须返回 Unit.INSTANCE因为该监听器在 kotlin 中并且该代码正在 java 中使用,所以返回 this 相当于在 java (void) 中不返回任何内容。

最佳答案

PagingData 运算符对单个项目进行操作,因此如果页面为空,它们不会被触发。
相反,您想在页面加载后通过观察 loadStateFlow 检查 PagingDataAdapter.itemCount。

loadStateFlow.map { it.refresh }
    .distinctUntilChanged()
    .collect {
        if (it is NotLoading) {
            // PagingDataAdapter.itemCount here
        }
    }
顺便说一句,null是 Paging 中的一个特殊值,表示占位符,因此您不应提供包含 null 的 Paging 页面s,这就是 Value 的下限的原因。 generic 不为空 Any而不是 Any?

关于android - 如何检查 Paging 3 库中的列表大小或空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64469375/

相关文章:

java - 使用联系人电话号码打开联系人列表中的联系人信息 Android Studio

android - 位置数据源不加载所有数据

android - 分页库使数据源无效

java - 在android中单击按钮时重新启动或刷新计时器

java - JNI 获取上下文

java - 我的切换中的 SharedPreferences 问题

Android分页库java.lang.IllegalArgumentException : MainThreadExecutor required

android - 如何使用列表大小与 Room 数据库返回的列表大小不同的 AAC 分页库

android - 在 Google Paging Library 3 中没有任何滚动的情况下,Api 调用不会一次又一次地停止调用

android - 如何使用 Paging 3 库更新单个项目