Home > Net >  Infinite loop in PagingSource when response is empty using Paging 3 library and Retrofit
Infinite loop in PagingSource when response is empty using Paging 3 library and Retrofit

Time:08-10

I'm using Paging 3 library and Retrofit to get data. My problem is that when the API response retrieve an empty list, instead of print nothing, it causes an infinite loop in my PagingSource class. How can I stop the loop? I want the possibility to get an empty response.

My PagingSource class:

    val responseData = mutableListOf<DataAPI>()
class DataAPIPagingSource(private val token:String,private val apiCalls:APICalls) : PagingSource<Int,DataAPI>{
    
    override fun getRefreshKey(...):Int?{
        return null
    }
    override suspend fun load(params : LoadParams<Int>):LoadResult<Int,DataAPI>{
        return try{
            val currentPage = params.key ?: 1
            val response = apiCalls.getData(token)
            response.body()?.let{
                Result.Success(it)  
            }?: run{
                Result.Failure(response.message(),response.code())
            }
            val data = response.body()?.listData ?: emptyList()
            responseData.addAll(data)
            LoadResult.Page(responseData,if(currentPage ==1) null else -1),currentPage.plus(1)
            

        }catch(e:Exception){
            LoadResult.Error(e)
        }   
    }
}

CodePudding user response:

The load function returns LoadResult.Page when the load was successful, which has three values: data, prevKey and nextKey. Documentation for the nextKey says:

nextKey - Key for next page if more data can be loaded in that direction, null otherwise

You always use currentPage 1 for the nextKey though, so paging thinks there are more pages to load and tries to load them. Set nextKey to null when there are no more data to load.

  • Related