簡體   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