1

我正在尝试使用Kotlin CoroutinesRetrofit实现 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)
    })
4

0 回答 0