我是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)
})
}
这是我创建的资源类处理异常(请提供我一个更好的,如果有)
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中显示异常或基于异常的消息。
您的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
,它可以通过LoadStateAdapter
,.addLoadStateListener
等以及.retry
进行反应。所有来自Paging的演示器api都公开了这些方法,例如PagingDataAdapter
: https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter
必须将错误处理程序传递给PagingSource
class MyPagingSource(
private val api: MyApi,
private val onError: (Throwable) -> Unit,
): PagingSource<Int, MyModel>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, YourModel> {
try {
...
} catch(e: Exception) {
onError(e) // <-- pass your error listener here
}
}
}