How to handle error in paging3 using Remote mediator with viewPager2

Viewed 71

I am using RemoteMediator to populate my Viewpager2. The view pager contains weekly data and it is in RTL format because i have to show data in descending order. current week, last week.... Please refer below pictures.

enter image description here

So i am able to fetch data and populate the DB properly. The problem i am facing is in Error Handling.

I went through LoadState documentation and not able to grasp fully. The LoadstateViewHolder extends RecyclerViewHolder. So will it work with ViewPager2 ?

The requirement I have is like below :

  1. If there is no data available in cloud, create a page and show "-" as data for all the dates for current week only. enter image description here

  2. If there is data available in local db and REFRESH is giving any error, PREPEND a page in viewpager with "-" data for current week.

enter image description here

I can not share the code for official purposes.. Any help will be appreciated.. Thanks.

1 Answers

In order to listen to RemoteMediator errors, you can add a LoadStateListener to your RecyclerView adapter as follows:

mAdapter = MyAdapter(...).apply {
    addLoadStateListener { loadState ->
        val mediatorLoadState: LoadState? = loadState.mediator?.refresh

        if (mediatorLoadState is LoadState.Error) {
            // Herein you can implement your fallback 
            // as per mediatorLoadState.error 
        }
    }
}

Likewise, you can change loadState.mediator?.xxx by the RemoteMediator's state you want to listen to.

Related