I am trying implement Android jetpack's paging library with Kotlin Coroutines and Retrofit. After debugging I found out that observation doesn't invoke on success of server response.
Am I missing something to have complete implementation?
This is my implementation of 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>) {
}
}
Code piece for observe
pageViewModel.allPosts.observe(viewLifecycleOwner, Observer {
Log.i("test", "aaa "+it.toString())
articlesAdapter.submitList(it)
})