【问题标题】:How to handle Kotlin Jetpack Paging 3 exceptions?如何处理 Kotlin Jetpack Paging 3 异常?
【发布时间】:2021-09-19 20:18:03
【问题描述】:

我是 kotlin 和 jetpack 的新手,我被要求处理来自 PagingData 的错误(异常),我不能使用 Flow,我只能使用 LiveData。

这是存储库:

class GitRepoRepository(private val service: GitRepoApi) {

    fun getListData(): LiveData<PagingData<GitRepo>> {
        return Pager(
            // Configuring how data is loaded by adding additional properties to PagingConfig
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false
            ),
            pagingSourceFactory = {
                // Here we are calling the load function of the paging source which is returning a LoadResult
                GitRepoPagingSource(service)
            }
        ).liveData
    }
}

这是视图模型:

class GitRepoViewModel(private val repository: GitRepoRepository) : ViewModel() {

    private val _gitReposList = MutableLiveData<PagingData<GitRepo>>()

    suspend fun getAllGitRepos(): LiveData<PagingData<GitRepo>> {
        val response = repository.getListData().cachedIn(viewModelScope)
        _gitReposList.value = response.value
        return response
    }

}

在我正在做的活动中:

  lifecycleScope.launch {
            gitRepoViewModel.getAllGitRepos().observe(this@PagingActivity, {
                recyclerViewAdapter.submitData(lifecycle, it)
            })
        }

这是我为处理异常而创建的 Resource 类(如果有,请给我一个更好的)

data class Resource<out T>(val status: Status, val data: T?, val message: String?) {

    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(Status.SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): Resource<T> {
            return Resource(Status.ERROR, data, msg)
        }

        fun <T> loading(data: T?): Resource<T> {
            return Resource(Status.LOADING, data, null)
        }
    }
}

如您所见,我正在使用 Coroutines 和 LiveData。我希望能够在异常从 Repository 或 ViewModel 发生时将其返回到 Activity,以便根据 TextView 中的异常显示异常或消息。

【问题讨论】:

  • 请勿发布代码图片或其他文字。将原文复制到您的问题中,并使用代码格式工具。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: kotlin kotlin-coroutines android-livedata android-jetpack android-paging-3


【解决方案1】:

您的GitRepoPagingSource 应该捕获可重试错误并将它们作为LoadResult.Error(exception) 转发给 Paging。

class GitRepoPagingSource(..): PagingSource<..>() {
    ...
    override suspend fun load(..): ... {
        try {
            ... // Logic to load data
        } catch (retryableError: IOException) {
            return LoadResult.Error(retryableError)
        }
    }
}

这将作为LoadState 暴露给 Paging 的演示者端,可以通过LoadStateAdapter.addLoadStateListener 等以及.retry 对其作出反应。 Paging 的所有 Presenter API 都公开了这些方法,例如 PagingDataAdapter: https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多