android - 从 PagingSource 的 LoadResult.Error 中提取 Throwable
问题描述
我的PagingSource加载一些数据。文档建议像这样捕获异常,以便将来处理LoadResult.Error。
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
return try {
...
throw SomeCatchableException()
...
} catch (e: SomeCatchableException) {
LoadResult.Error(e)
} catch (e: AnotherCatchableException) {
LoadResult.Error(e)
}
}
但是当我尝试以这种方式处理它时:
(adapter as PagingDataAdapter).loadStateFlow.collectLatest { loadState ->
when (loadState.refresh) {
is LoadState.Loading -> {
// *do something in UI*
}
is LoadState.Error -> {
// *here i wanna do something different actions, whichever exception type*
}
}
}
我想知道哪个 Exteption 会被捕获,因为我在参数LoadResult.Error(e)中传递了它(Throwable ) 。
我如何知道 loadState 处理中异常的类型?
解决方案
您可以在 LoadState.Error 案例中从 loadState.refresh 捕获错误,您只是错过了将 loadState.refresh 转换为 LoadState.Error。或者试试这种方式:
when (val currentState = loadState.refresh) {
is LoadState.Loading -> {
...
}
is LoadState.Error -> {
val extractedException = currentState.error // SomeCatchableException
...
}
}
推荐阅读
- python - Python 减号和加号函数颠倒了?
- ios - 无法让 Codable 与继承一起工作
- .net - Postgres 和 .Net - 连接池 - 最佳实践
- php - 如何使用命名空间创建数组到 SOAPXML?
- java - 使用泛型接口中的方法
- python - 我想在 tkinter 中调用另一个类。我有 2 个类,我不能在我的窗口类下面调用数据库类
- python - 打印 void 函数执行函数
- javascript - 如何在谷歌脚本的电报机器人中键入多列消息
- oracle - 如何在 PL/SQL 中制作一个好的程序?
- javascript - 如何将每个项目放入p标签+最后清除innerHTML