【发布时间】:2021-09-19 20:18:03
【问题描述】:
我是 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)
}
}
}
如您所见,我正在使用 Coroutines 和 LiveData。我希望能够在异常从 Repository 或 ViewModel 发生时将其返回到 Activity,以便根据 TextView 中的异常显示异常或消息。
【问题讨论】:
-
请勿发布代码图片或其他文字。将原文复制到您的问题中,并使用代码格式工具。
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
标签: kotlin kotlin-coroutines android-livedata android-jetpack android-paging-3