![](/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.