There is great sample @yigit related to the Paging library which also shows how to handle progress bar, error and Retry in Recyclerview. So Basically he is creating a Listing.kt
data class which consist of the NetworkState
and PagedList
Like below
Listing.kt
data class Listing<T>(
// the LiveData of paged lists for the UI to observe
val pagedList: LiveData<PagedList<T>>,
// represents the network request status to show to the user
val networkState: LiveData<NetworkState>,
// represents the refresh status to show to the user. Separate from networkState, this
// value is importantly only when refresh is requested.
val refreshState: LiveData<NetworkState>,
// refreshes the whole data and fetches it from scratch.
val refresh: () -> Unit,
// retries any failed requests.
val retry: () -> Unit)
NetworkState.kt
enum class Status {
RUNNING,
SUCCESS,
FAILED
}
@Suppress("DataClassPrivateConstructor")
data class NetworkState private constructor(
val status: Status,
val msg: String? = null) {
companion object {
val LOADED = NetworkState(Status.SUCCESS)
val LOADING = NetworkState(Status.RUNNING)
fun error(msg: String?) = NetworkState(Status.FAILED, msg)
}
}
RedditPostRepository.kt
interface RedditPostRepository {
fun postsOfSubreddit(subReddit: String, pageSize: Int): Listing<RedditPost>
enum class Type {
IN_MEMORY_BY_ITEM,
IN_MEMORY_BY_PAGE,
DB
}
}
The SubRedditViewModel.k
observe the Listing<RedditPost>
from RedditPostRepository.kt
notify to UI about the state and data and UI updates the view accordingly. To know more about how the NetworkState
propagate from Datasource to ViewModel Look at the PageKeyedSubredditDataSource.kt and SubRedditDataSourceFactory.kt
Here is the Link to the Google sample by @yigit.