Activity with multiple ViewModels

Martin picture Martin · Sep 21, 2017 · Viewed 15.9k times · Source

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).

Answer

According to the open/closed principle, you should create three different ViewModels. The complexity isn't increased that much, and you are gaining the ability to move one ViewModel (or just reuse it) with the corresponding RecyclerView to the another Activity very easily.

Of course, sometimes breaking rules makes sense - for example if you know, there is no chance, that RecyclerView will be reused or moved to another screen, and then you can go for simpler solution with one ViewModel.

The same situation if the ViewModel (even with the 3 lists) is likely to stay always very simple (just three LiveData fields, just a few lines of code to populate them), you can break this rule.

However violation of O/CP is not a good practice - it's just a conscious breaking of rule.