当我不使用 ContiguousPagedList 时,ContiguousPagedList onPageError

ContiguousPagedList onPageError while I'm not using ContiguousPagedList

我有定义 loadInitialloadRange 的 PositionalDataSource 的实现。分页工作正常,但在某些边界条件下(可能与退出屏幕时加载正在进行的下一页有关)应用程序崩溃 androidx.paging.ContiguousPagedList.onPageError (ContiguousPagedList.java:153)。但是每个 https://developer.android.com/reference/android/arch/paging/PositionalDataSource 我的来源不是连续的?

崩溃发生在 ContiguousPagedList 的 onPageError 下,符合 "todo":

public void onPageError(@PageResult.ResultType int resultType,
        @NonNull Throwable error, boolean retryable) {

   LoadState errorState = retryable ? LoadState.RETRYABLE_ERROR : LoadState.ERROR;

    if (resultType == PageResult.PREPEND) {
        mLoadStateManager.setState(LoadType.START, errorState, error);
    } else if (resultType == PageResult.APPEND) {
        mLoadStateManager.setState(LoadType.END, errorState, error);
    } else {
        // TODO: pass init signal through to *previous* list
        throw new IllegalStateException("TODO");
    }
}

我的配置没有使用占位符,我也没有将总数传递给 onResult of LoadInitialCallback。分页库版本为2.1.1

我遇到了相同的行为,因为当我的 PageKeyedDataSource 实现的 loadInitialloadAfter 方法发生异常时,我调用了 callback.onError(e)。为了防止应用程序崩溃,我删除了 callback.onError(e) 行。我知道这不是解决方案,但至少我的应用程序不会随机崩溃。

示例代码(Kotlin+协程传入)

override fun loadInitial(params: LoadInitialParams<Long>, callback: LoadInitialCallback<Long, Beer>) {
    scope.launch {
        try {
            val response =
                BackendService.client.getBeers(
                    name = searchQueryNullable,
                    page = 1,
                    pageSize = params.requestedLoadSize
                )
            callback.onResult(response, 1, 2)
        } catch (e: Exception) {
            Log.e(tag, "Error loadInitial", e)
            // callback.onError(e) <-- this is the line that generates the crash: comment it
        }
    }
}

至少目前(版本 2.1.1)没有好的和干净的解决方案。

ContiguousPagedList 不支持初始化错误处理。 您必须为加载状态和自定义重试实现并行流。

参见示例 in the official architecture components samples library。 Yigit Boyar 通过从存储库返回自定义 Listing 对象实现了几个流。

data class Listing<T>(
        // the LiveData of paged lists for the UI to observe
        val pagedList: LiveData<PagedList<T>>,
        // represents the network request status to show to the user
        val networkState: LiveData<NetworkState>,
        // represents the refresh status to show to the user. Separate from networkState, this
        // value is importantly only when refresh is requested.
        val refreshState: LiveData<NetworkState>,
        // refreshes the whole data and fetches it from scratch.
        val refresh: () -> Unit,
        // retries any failed requests.
        val retry: () -> Unit)

查看数据源的实现here

更新

经过多次不同的尝试,我最终从架构的核心部分中删除了 Jetpack,并将其仅保留在视图模型中,现在对我来说看起来干净多了。你可以阅读它 here