从 PagingSource 的 LoadResult.Error 中提取 Throwable

Extract Throwable from LoadResult.Error of PagingSource

我的 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*
                    }
                }
            }

我想知道哪个扩展会被捕获,因为我在参数 LoadResult.Error(e)[=25 中传递了它 (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
       ...
   }
}