提问者:小点点

处理Paging3 Android中的HttpException


我有一个pagingsource如下所示:

class NotificationPagingSource(
    private val tayehAPI: TayehAPI,
    private val token: String,
) : PagingSource<Int, Notification>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Notification> {
        val nextPageNumber = params.key ?: STARTING_PAGE_INDEX

        return try {
            val response = tayehAPI.getNotifications(
                tokenString = token,
                page = nextPageNumber,
                perPage = params.loadSize
            )
            val notifications = response.objects

            LoadResult.Page(
                data = notifications,
                prevKey = if (nextPageNumber == STARTING_PAGE_INDEX) null else nextPageNumber - 1,
                nextKey = if (notifications.isEmpty()) null else nextPageNumber + 1
            )
        } catch (e: IOException) {
            LoadResult.Error(e)
        } catch (e: HttpException) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Notification>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }
}

我想处理httpexceptions(如403或404)。我怎样才能做到这一点呢?


共1个答案

匿名用户

您需要将AddLoadStateListener添加到分页适配器,如下所示:

notificationAdapter.addLoadStateListener { loadState ->
            val errorState = when {
                loadState.append is LoadState.Error -> loadState.append as LoadState.Error
                loadState.prepend is LoadState.Error ->  loadState.prepend as LoadState.Error
                loadState.refresh is LoadState.Error -> loadState.refresh as LoadState.Error
                else -> null
            }
            errorState?.let {
                if (errorState.error.localizedMessage == "HTTP 403 Forbidden") {
                    AlertDialog.Builder(requireContext())
                        .setMessage(R.string.token_expire)
                        .setPositiveButton("Ok") { _, _ ->
                            findNavController().navigate(
                                NotificationFragmentDirections.actionGlobalHomeFragment()
                            )
                        }
                        .setCancelable(false)
                        .create()
                        .show()

                }
            }
        }