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
归档时间: |
|
查看次数: |
5345 次 |
最近记录: |