简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM