我正在尝试使用 Kotlin 协同程序和改造来实现Android jetpack的分页库。 调试后,我发现观察不会在服务器响应成功时调用。
我缺少一些可以完全实施的东西吗?
这是我 PageKeyedDataSource
的实现class NewsDataSource(private val scope: CoroutineScope) : PageKeyedDataSource<Long, PostArticle>() {
private val postApi = PostService().postApi
override fun loadInitial(
params: LoadInitialParams<Long>,
callback: LoadInitialCallback<Long, PostArticle>
) {
scope.launch {
try {
val response = postApi.getPosts(page = 1L)
when {
response.isSuccessful -> {
val serverResponse: ServerResponse? = response.body()
val responsePagination: ResponsePagination? = serverResponse?.response
val responsePosts = responsePagination?.results
val posts = responsePosts?.map { it.convert() }
val nextPageKey = serverResponse?.currentPage?.let { it + 1L }
callback.onResult(posts ?: listOf(), null, nextPageKey)
}
}
} catch (e: Exception) {
Log.e("NewsDataSource", "Failed to fetch data!")
}
}
}
override fun loadAfter(params: LoadParams<Long>, callback: LoadCallback<Long, PostArticle>) {
}
override fun loadBefore(params: LoadParams<Long>, callback: LoadCallback<Long, PostArticle>) {
}
}
观察代码段
pageViewModel.allPosts.observe(viewLifecycleOwner, Observer {
Log.i("test", "aaa "+it.toString())
articlesAdapter.submitList(it)
})