mardi 26 novembre 2019

What is the recommended way to update a LiveData variable in ViewModel from Repository in the MVVM design pattern?

I am a beginner in MVVM architecture. I want to retrieve a list of items from the database and I want to keep track of the number of items that i retrieve. I am following the MVVM design pattern. The following is the first approach I thought of:

class SampleViewModel extends ViewModel
{
    private MutableLiveData<Integer> count = new MutableLiveData<>();

    getItems();

    public void getItems()
    {
        List<String> items = new ArrayList<>();

        /*
        * I am skipping the code to access the database and retrieving the list
        * */

        for (String item : items)
        {
            items.add(item);
            count.setValue(items.size());
        }
    }

    LiveData<Integer> GetCount()
    {
        return count;
    }
}

Then observe the count data from my activity. But, then I learned that, it is recommended to do database related tasks from the Repository and according to this doc, LiveData variable is not recommended to be passed from ViewModel to Repository. So, my question is how can I update count variable from Repository or in other words, What is the recommended way to update a LiveData variable in ViewModel from Repository, so that it can be observed fro the activity properly?

Aucun commentaire:

Enregistrer un commentaire