Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity with multiple ViewModels

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

like image 808
Martin Avatar asked Sep 21 '17 09:09

Martin


People also ask

Can fragment have 2 Viewmodels?

In fact you can have multiple view models for a single fragments doing different things for you.

Can an activity have multiple ViewModel?

According to the open/closed principle, you should create three different ViewModel s. 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.

Can multiple fragments share a ViewModel?

Multiple fragments in the app will access the shared ViewModel using their activity scope. It is a common use case to share data between fragments in most production apps.

Can two activity share same ViewModel?

You can't share a ViewModel across Activities. That's specifically one of the downsides of using multiple activities as per the Single Activity talk.


2 Answers

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.

like image 119
Piotr Aleksander Chmielowski Avatar answered Oct 11 '22 13:10

Piotr Aleksander Chmielowski


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.

like image 36
guglhupf Avatar answered Oct 11 '22 15:10

guglhupf