首页 > 解决方案 > 如何将 Paging 3 从 Kotlin Flow 移植到 Java?- 找不到 PagingDataFlow.create 函数

问题描述

Paging 3 几天前刚刚发布。

目前,我们正在将以下 Paging 3 示例代码从 Kotlin 移植到 Java。

https://github.com/android/architecture-components-samples/blob/a2151cf66483560f76b041ba95ce96e931c50caf/PagingSample/app/src/main/java/paging/android/example/com/pagingsample/CheeseViewModel.kt

科特林

/**
 * We use the Kotlin API to construct a [Flow]<[PagingData]>. Java developers should use the
 * Java API: `PagingDataFlow.create`
 */
val allCheeses = Pager(
    PagingConfig(
        /**
         * A good page size is a value that fills at least a few screens worth of content on a
         * large device so the User is unlikely to see a null item.
         * You can play with this constant to observe the paging behavior.
         *
         * It's possible to vary this with list device size, but often unnecessary, unless a
         * user scrolling on a large device is expected to scroll through items more quickly
         * than a small device, such as when the large device uses a grid layout of items.
         */
        pageSize = 60,

        /**
         * If placeholders are enabled, PagedList will report the full size but some items might
         * be null in onBind method (PagedListAdapter triggers a rebind when data is loaded).
         *
         * If placeholders are disabled, onBind will never receive null but as more pages are
         * loaded, the scrollbars will jitter as new pages are loaded. You should probably
         * disable scrollbars if you disable placeholders.
         */
        enablePlaceholders = true,

        /**
         * Maximum number of items a PagedList should hold in memory at once.
         *
         * This number triggers the PagedList to start dropping distant pages as more are loaded.
         */
        maxSize = 200
    )
) {
    dao.allCheesesByName()
}.flow

爪哇

构建 aPagingConfig不是什么大问题。

final int pageSize = 60;
final int prefetchDistance = pageSize;
final boolean enablePlaceholders = false;
final int initialLoadSize = pageSize * PagingConfig.DEFAULT_INITIAL_PAGE_MULTIPLIER;
final int maxSize = PagingConfig.MAX_SIZE_UNBOUNDED;
final int jumpThreshold = PagingSource.LoadResult.Page.COUNT_UNDEFINED;

PagingConfig pagingConfig = new PagingConfig(
        pageSize,
        prefetchDistance,
        enablePlaceholders,
        initialLoadSize,
        maxSize,
        jumpThreshold
);

但是,我们被卡住了。

下面的代码注释引起了我们的注意。

Java 开发人员应该使用 Java API:PagingDataFlow.create

根据代码注释,Java 开发人员应该使用PagingDataFlow.create. 但是,从 IDE 中,我们真的找不到名为androidx.paging.PagingDataFlow.

我们期望有LiveData我们可以观察到的。Kotlin 的流程/协程不是我们在 Java 领域所期望的。

知道我们可以如何使用PagingDataFlow.create吗?

标签: javaandroidkotlinandroid-paging

解决方案


不幸的是,此文档已过时,因为我在旧快照之上编写了此示例,并且忘记在发布前对其进行更新。

您正在寻找的 API 是 Pager 之上的扩展属性。在 Java 中,您应该寻找 PagingLiveData.getLiveData(Pager)

有关更多示例,请参见此处:https ://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#g​​uava-livedata


推荐阅读