我是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
}
}
这是ViewModel:
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返回到活动,以便在TextView中显示异常或基于异常的消息。
发布于 2021-09-21 20:30:48
您的GitRepoPagingSource应该捕获可重试的错误,并将它们作为LoadResult.Error(exception)转发给分页。
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都公开这些方法,如PagingDataAdapter:https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter
https://stackoverflow.com/questions/69246807
复制相似问题