![](/img/trans.png)
[英]How to dynamically modify variables in PagingSource class, Paging Library 3.0
[英]PagingSource from paging library 3 with callback as result
目前,我正在尝试迁移到Android的新的paging 3库,但是如果我看对了,我不能:(
我正在使用 AWS Amplify 作为我的后端数据源,并希望将查询包含到分页库中的 PaginSource class 的新负载 function 中。
override suspend fun load(params: LoadParams<String>): LoadResult<String, Car> {
val query = ListCarsQuery.builder().limit(params.loadSize).build()
appSyncClient.query(query)
.responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
.enqueue(
object : GraphQLCall.Callback<ListCarsQuery.Data>() {
override fun onResponse(response: Response<ListCarsQuery.Data>) {
val result = CarTransformer.toModels(response)
// Here is my actual result list
}
override fun onFailure(e: ApolloException) {
TODO("Not yet implemented")
}
}
)
//How can I add my result list here ?
return LoadResult.Page(
data = listOf(),
prevKey = null,
nextKey = ""
)
因为方法 enqueues 给了我一个无效的返回,所以我不知道如何等待它或触发回调,就像在分页库 2 中一样。在分页 2 中,我可以选择调用 callback.onResult(result.data, result. nextLink) 方法中的 enqueue().onResponse function 而无需返回任何内容。
有没有办法实现它,还是我应该坚持使用分页 2?
Paging3 不提供回调 API(还),因此您需要将其包装到 RxJava Single、Guava ListenableFuture 或暂停的 Kotlin 协程中。
PagingSource 的 Rx 版本在paging-rxjava2/3
工件中可用,而 Guava 在paging-guava
中。
就实际转换而言,列出所有可能性会很多,但例如有 Kotlin 协程构建器允许您在暂停上下文中包装和等待 xallbacks。 以suspendCancellableCoroutine为例,你基本上得到一个Continuation
object,你可以调用resume(result)
。
正如@dlam 提到的,您可以使用suspendCacellableCoroutine或suspendCoroutine如下:
使用您的示例,它将是:
override suspend fun load(params: LoadParams<String>): LoadResult<String, Car> {
return suspendCoroutine { continuation ->
val query = ListCarsQuery.builder().limit(params.loadSize).build()
appSyncClient.query(query)
.responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
.enqueue( object : GraphQLCall.Callback<ListCarsQuery.Data>() {
override fun onResponse(response: Response<ListCarsQuery.Data>) {
val result = CarTransformer.toModels(response)
//Here is where you use your continuation object in order to resume the suspended function
continuation.resume(LoadResult.Page(
data = result,
prevKey = null,
nextKey = ""
))
}
override fun onFailure(e: ApolloException) {
TODO("Not yet implemented")
continuation.resume(LoadResult.Error(e))
}
}
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.