Search code examples
javaandroidandroid-recyclerviewandroid-livedataandroid-viewmodel

How to correctly code a RecyclerView with ViewModel and LiveData


I have been trying to make a RecyclerView with with endless scrolling that loads it's data from a online API using ViewModel and MutableLiveData. I have everything working except the endless scrolling. Now as I am trying to get this working I fear I am just plain doing something in the base wrong(mainly with the MutableLiveData). So short of showing my whole app's code (which I eill do) I don't how else to ask about my problem. Note: This is my first time working with any of this.

So, instead of do that (because I don't know if anyone would take the time to do that) I will just ask for some examples (even a tutorial) of how to do it correctly.

I have looked and looked, but I can't find any examples that have a RecyclerView with ViewModel,MutableLiveData, Web requests(I am using Volley) and endless scrolling(It wouldn't have to have this one), inside a Fragment, in java.

And just so no one thinks I am looking for free code, I have spent the last 4 months working on just this.


Solution

  • Android Team has made a library for paging as it was a major pain point for many developers for years.

    https://developer.android.com/topic/libraries/architecture/paging/v3-overview

    The Paging library helps you load and display pages of data from a larger dataset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently. The components of the Paging library are designed to fit into the recommended Android app architecture, integrate cleanly with other Jetpack components, and provide first-class Kotlin support.

    You can also check the codelab on this link for a step by step guide.

    https://developer.android.com/topic/libraries/architecture/paging/v3-overview#codelabs


    For external or other third party article help check below:

    This article explains a scalable architecture on how to build an efficient RecyclerView with paging.

    https://medium.com/@shashankmohabia/android-paging-efficient-way-to-populate-recycler-view-dynamically-31f39f35cdf9

    After reading the article and understanding how this works, please check this sample project. It uses Retrofit instead of Volley. But you will get the understanding of the full implementation by looking at the code.

    https://github.com/Vanethos/Android-Paging-Example

    Now for the setting up of the Paging Library, you can check out this article which explains step by step how to include it in the gradle.

    https://androidwave.com/android-paging-library/