我是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)
}
}
}
正如您所看到的,我使用的是协同程序和LiveData。我希望能够在发生异常时将其从仓库或ViewModel返回到Activity,以便在TextView中显示异常或基于异常的消息。
2条答案
按热度按时间cwtwac6a1#
您的
GitRepoPagingSource
应该捕获可重试的错误,并将它们作为LoadResult.Error(exception)
传递给Paging。它以
LoadState
的形式公开给Paging的表示器端,可以通过LoadStateAdapter
、.addLoadStateListener
等以及.retry
对其作出React。Paging的所有表示器API都公开这些方法,例如PagingDataAdapter
:https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapteruqdfh47h2#
您必须将错误处理程序传递给
PagingSource