首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何处理Kotlin Jetpack Paging 3异常?

如何处理Kotlin Jetpack Paging 3异常?
EN

Stack Overflow用户
提问于 2021-09-19 20:18:03
回答 1查看 770关注 0票数 2

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

这是存储库:

代码语言:javascript
复制
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
    }
}

这是ViewModel:

代码语言:javascript
复制
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
    }

}

在我正在做的练习中:

代码语言:javascript
复制
  lifecycleScope.launch {
            gitRepoViewModel.getAllGitRepos().observe(this@PagingActivity, {
                recyclerViewAdapter.submitData(lifecycle, it)
            })
        }

这是我创建的用来处理异常的Resource类(如果有,请提供一个更好的)

代码语言:javascript
复制
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)
        }
    }
}

如你所见,我使用的是协程和LiveData。我希望能够在异常发生时将其从存储库或ViewModel返回到活动,以便在TextView中显示异常或基于异常的消息。

EN

回答 1

Stack Overflow用户

发布于 2021-09-21 20:30:48

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

代码语言:javascript
复制
class GitRepoPagingSource(..): PagingSource<..>() {
    ...
    override suspend fun load(..): ... {
        try {
            ... // Logic to load data
        } catch (retryableError: IOException) {
            return LoadResult.Error(retryableError)
        }
    }
}

这将作为LoadState公开给分页的呈现者端,它可以通过LoadStateAdapter.addLoadStateListener等以及.retry进行响应。分页中的所有presenter API都公开这些方法,如PagingDataAdapterhttps://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69246807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档