我正在使用 Paging 3 库和 Retrofit 来获取数据。我的问题是,当 API 响应检索到一个空列表时,它不会打印任何内容,而是会导致我的 PagingSource 类中出现无限循环。我怎样才能停止循环?我希望有可能得到空的答复。
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)
}
}
}
load函数在加载成功时返回
LoadResult.Page
,有三个值:data
、prevKey
和nextKey
。 nextKey
的文档说:
- 如果可以在该方向加载更多数据,则为下一页的键,否则为 nullnextKey
您总是使用
currentPage + 1
作为 nextKey
,因此分页认为还有更多页面需要加载并尝试加载它们。当没有更多数据要加载时,将 nextKey
设置为 null
。