繁体   English   中英

使用 Paging 3 库和 Retrofit 响应为空时 PagingSource 中的无限循环

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

我正在使用 Paging 3 库和 Retrofit 来获取数据。 我的问题是,当 API 响应检索一个空列表,而不是什么都不打印时,它会在我的 PagingSource class 中导致无限循环。 我怎样才能停止循环? 我希望有可能得到一个空洞的回应。

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

加载成功后加载 function 返回LoadResult.Page ,其中包含三个值: dataprevKeynextKey nextKey的文档说:

nextKey - 如果可以在该方向加载更多数据,则为下一页的密钥,否则为 null

你总是使用currentPage + 1作为nextKey ,所以 paging 认为有更多的页面要加载并尝试加载它们。 当没有更多数据要加载时,将nextKey设置为null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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