Skip to content

Instantly share code, notes, and snippets.

@Wajahat-Jawaid
Last active November 7, 2022 09:51
Show Gist options
  • Save Wajahat-Jawaid/9f0025b83e3e1a2d45bd80f978af888d to your computer and use it in GitHub Desktop.
Save Wajahat-Jawaid/9f0025b83e3e1a2d45bd80f978af888d to your computer and use it in GitHub Desktop.
// ...
private fun fetchPosts() {
// Verify if Internet is present
if (!isNetworkAvailable(requireContext())) {
hideLoadingAnimation()
showErrorView(R.string.no_internet)
return
}
mViewModel.getPosts()
mViewModel.postsResponse.observe(viewLifecycleOwner) { (status, data): Resource<PostsResponse?> ->
if (status === Status.SUCCESS) {
// If though API succeeded, but maybe no posts are present for now, then we need to display the
// error message
if (data?.posts == null) {
showErrorView(R.string.no_data_found)
return@observe
}
// Posts list fetched from the API
val responsePosts = data.posts
// Populating the generic list of #PostAdapterModel so as to handle the header views as well
val formattedPosts: MutableList<PostAdapterModel> = ArrayList()
// ...
mapDataOnRecyclerView(formattedPosts)
} else if (status === Status.ERROR) {
// Tip: You can reproduce this issue by changing the URL to something wrong so that we're sure that
// the error occurs
hideLoadingAnimation()
showErrorView(R.string.unexpected_error)
}
}
}
private fun mapDataOnRecyclerView(posts: List<PostAdapterModel>) {
val recyclerView = requireView().findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.addItemDecoration(VerticalItemDecoration(requireContext(), 1))
recyclerView.adapter = PostsAdapter(posts, viewLifecycleOwner, mViewModel, this)
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment