Search code examples
androidandroid-paging-3

Extract Throwable from LoadResult.Error of PagingSource


My PagingSource load some data. Documentation recomended catch exceptions like this, for some processing LoadResult.Error in future.

 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)
            }
        }

But when i try process it this way:

(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*
                    }
                }
            }

I want to know which Exteption will be catched, coz i pass it (Throwable) in params LoadResult.Error(e).

How do i know the type of the exception in loadState processing?


Solution

  • You can get catched error from loadState.refresh in your LoadState.Error case, you just miss a cast loadState.refresh to LoadState.Error. Or try this way:

    when (val currentState = loadState.refresh) {
       is LoadState.Loading -> {
          ...
       }
       is LoadState.Error -> {
           val extractedException = currentState.error // SomeCatchableException
           ...
       }
    }