Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progressbar and error message with Paging Library

Paging Library is amazing. But I find that lacks this features:

  • Dispatch a view when data is loading. Assuming I am extending PageKeyedDataSource: a view on top when loadInitial is called, a view on bottom of the list when loadAfter is called. Views should disappear when callback is invoked.
  • Dispatch a view when there is an error.
  • Swipe to refresh

As this is not possible right now, does anyone know a way to do it using PagingLibrary? At least a way to use different views in the same list.

like image 532
Damia Fuentes Avatar asked Jan 09 '18 17:01

Damia Fuentes


1 Answers

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.

like image 164
waleedsarwar86 Avatar answered Oct 31 '22 03:10

waleedsarwar86