Solve Network-Database (Room) by Android Jetpack Paging library and Coroutine — Part 2: Refresh

An Nguyen
2 min readApr 11, 2020

This article is the second part of my series about Solve Network-Database (Room) by Android Jetpack Paging library and Coroutine:

In the first article, We went through how to solve network-database(room) by using Paging library and Coroutine. This article is about adding a refresh feature to the flow.

Why do we need to have a refresh feature?

With the first article, your app is able to make:

  • An API call for the first page of a subReddit.
  • Store data of the first page into the app’s local database.
  • Make multiple API calls for the next pages of a SubReddit.
  • Store data of those next pages into the apps’ local database.

What if the user wants to view the latest post in the current subReddit?

What if the user wants to view a different subReddit?

What does the refresh function do?

  • Make an API call for the first page of a subReddit. (could be different with the last refresh).
  • Clear all post to belong to the requested subReddit to maintain the index order in the app’s local database.
  • Insert new posts to the app’s local database.

How do we make it happen?

We need to add a “trigger” into PagingPosts object which allows viewModel to call the refresh function.

To trigger the refresh function, viewModel only needs to:

Let’s come back to the loadPostBySubName method where we set up our PagingPost object.

Before, we had networkState to stream all network status of calling for the first page or next page of data in the previous article. Now we split them to refreshState and loadMoreState. I believe their names tell us their purposes.

Another thing we initialize in the below method is the refresh trigger method. Because the trigger could be called from any thread so it is better to utilize LiveData to trigger a network call to refresh data.

As you can see in the method above, refresh triggers the refreshTrigger LiveData which triggers the Transformations.switchMap to call refreshing function.

Now, all we need to do is observe the refreshState of PagingPost object otherwise Transformations.switchMap won’t be triggered because LiveData needs to have an active observer to function normally.

Check out the project on github.

Demo

Conclusion

We just finished the full set up for properly using Pagination Library with the support of LiveData and Coroutine in MVVP pattern. I hope you enjoy the article and find it helpful to you.

Thank you.

--

--

An Nguyen

Dad, Husband, Android Developer, Manga/Video Game Lover, Unity3d learner.