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

Sha*_*dow 6 android android-paging android-paging-library

按照此处提供的说明,我已经能够成功实现新的 alpha07 版本的 Paging 3 库:https : //developer.android.com/topic/libraries/architecture/paging/v3-paged-data#g​​uava-livedata

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

目前,这是我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));
Run Code Online (Sandbox Code Playgroud)

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

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

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

我有一个附加LoadStateListener我的转接器,监听时LoadTypeREFRESHLoadState的NotLoading,再检查是否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

}
Run Code Online (Sandbox Code Playgroud)

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

dla*_*lam 7

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

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

loadStateFlow.map { it.refresh }
    .distinctUntilChanged()
    .collect {
        if (it is NotLoading) {
            // PagingDataAdapter.itemCount here
        }
    }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,null是 Paging 中的一个特殊值,表示占位符,所以你不应该给出包含nulls 的Paging 页面,这就是为什么Value泛型的下限是非空Any而不是Any?

  • 在 Java 中,您可以使用 loadStateListener 来代替,或者如果您使用 rxjava,则可以将流转换为 rx 流。如果这是您首选的流 API,还可以使用 toLiveData 帮助程序 (2认同)