如何解决Paging 3.0库不会停止从服务器获取项目
我正在使用Paging 3.0库从服务器中加载一些数据,目前正面临服务器返回少量项目(即1,2个项目)的问题。现在发生的是,分页库不断调用同一端点。我的问题与问题1相似,我猜2只是我的Paging 3.0版本和方法不同。
这是我的PagingSource:
private const val STARTING_PAGE_INDEX = 0
class MyPagingSource(
private val apiService: MyProductService,private val query: String
) : PagingSource<Int,ProductResponse>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int,ProductResponse> {
val position = params.key ?: STARTING_PAGE_INDEX
return try {
val response = apiService.searchProduct(STARTING_PAGE_INDEX,query,params.loadSize)
val products = response.data?.records ?: emptyList()
LoadResult.Page(
data = products,prevKey = if (position == STARTING_PAGE_INDEX) null else position - 1,nextKey = if (products.isEmpty()) null else position + 1
)
}catch (exception: IOException){
return LoadResult.Error(exception)
}catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}
PagingConfig:
override fun searchProduct(
product: String
): Flow<PagingData<ProductResponse>> {
return Pager(
config = PagingConfig(
pageSize = RECORDS_PER_PAGE,enablePlaceholders = false,maxSize = MAX_RECORDS_PER_PAGE
),pagingSourceFactory = { MyPagingSource(apiService,product) }
).flow
}
companion object {
private const val RECORDS_PER_PAGE = 6
private const val MAX_RECORDS_PER_PAGE = 20
}
在我的ViewModel中,我有这个:
private var currentQueryValue: String? = null
private var currentSearchResult: UIEvent<Flow<PagingData<ProductResponse>>>? = null
fun searchProduct(query: String): UIEvent<Flow<PagingData<ProductResponse>>> {
val lastResult = currentSearchResult
if (query == currentQueryValue && lastResult != null) {
return lastResult
}
currentQueryValue = query
val newResult: Flow<PagingData<ProductResponse>> = dataSource.searchProduct(query)
.cachedIn(viewModelScope)
currentSearchResult = UIEvent(newResult)
return UIEvent(newResult)
}
在片段中,我有这个:
private var searchProductJob: Job? = null
private val viewModel by viewModels<MyViewModel> { viewModelProviderFactory }
....
private fun searchProduct(queryString: String) {
searchProductJob?.cancel()
searchProductJob = lifecycleScope.launch {
viewModel.searchProduct(queryString.trim().toLowerCase(Locale.getDefault()))
.getContentIfNotHandled()?.let { pagingData ->
pagingData.collectLatest {
productResultAdapter.submitData(it)
search_product_recycler_view.scrollToPosition(0)
}
}
}
}
我将对如何进行此操作提出任何建议:)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com(将#修改为@)