Activity with multiple ViewModels

Viewed 26538

I have an Activity that contains 3 RecyclerViews. I need populate RecyclerViews with data from remote repository (3 different requests). Can I use multiple ViewModels in the Activity, or is there any better solution (best practice).

4 Answers

In this case I would recommend to use one view model which populates three different LiveData objects. This way the UI can get updated whenever one of your three requests gets a response. For details how to use a RecyclerView with LiveData take a look into the Google Example.

I think having multiple viewmodels per activity only increases complexity and I do not see any value in doing that.

I got two recyclerview in a fragment. I think that use two ViewModels would be better. Cause different recyclerviews got their own data request, and state handling especially connections error. In this case separate into different ViewModels would not increase the the complexity, but I think it well fit the rule of decupling

Even simpler, you can have one ViewModel, that uses one service class, which in turn uses the three repositories to get the data. For example:

XActivity --> XViewModel --> XService --> {Arepository, Brepository, Crepository}

Related