如何处理 Kotlin Jetpack Paging 3 异常?

Roy*_*yek 7 kotlin android-livedata android-jetpack kotlin-coroutines android-paging-3

我是 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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是视图模型:

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
    }

}
Run Code Online (Sandbox Code Playgroud)

在我正在做的活动中:

  lifecycleScope.launch {
            gitRepoViewModel.getAllGitRepos().observe(this@PagingActivity, {
                recyclerViewAdapter.submitData(lifecycle, it)
            })
        }
Run Code Online (Sandbox Code Playgroud)

这是我创建的用于处理异常的 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

dla*_*lam 11

GitRepoPagingSource应该捕获可重试的错误并将它们作为LoadResult.Error(exception).

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

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

  • 问题是 PagingData **不是** 有状态的,它只有在有 UI 观察它并且 UI 是收集此状态的地方时才起作用。因此,来自 Paging 的加载错误目前只能从 UI 层看到,如果您想要单个对象 UDF,则需要将其作为 UI 信号单独发送回 VM。 (2认同)