Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM with Android Architecture Components

I'm exploring the new Android Architecture Components and looking to implement it into an Android app. I am firmillair with MVVM as I use the paradigm on iOS development. Having read through the Android Architecture Components guide, provided by Google: https://developer.android.com/topic/libraries/architecture/guide.html

I have just a few questions...

In the above mentioned guide, Google use the UserRepository class that access these web service API - they go on to make this class a Singleton which is probably fine, if there were only ever one screen on the app that needed data from a REST API.

My concern, is this; it seems Google advocate the need to create a repository class on a per-ViewModel basis. This sounds very wrong to me, in having so many Singlton classes in the app. If we were to have 10 screens, with ten ViewModels - each needing its own Repository module - we then have ten singletons in our app. From an iOS dev perspective, this is wrong to have so many.

The solution to this, would be to have one mediator (Repository) class, that has public methods, exposing the API to get data from a REST API. The Web service part, would be in its own class. That way, we have a decent separation of concerns.

Is it best practice, to have one repository class, per, ViewModel - or to have one per app? I'm not 100% sure on this.

Lastly, I have the same concern when it comes to Room- is Google saying we create a DB on a per ViewModel bases or just one DB per app?

like image 804
Robert J. Clegg Avatar asked Oct 18 '22 09:10

Robert J. Clegg


1 Answers

I don't think the architecture guide suggests to create a separate repository class for each ViewModel. In the example that is shown Google uses a library called Dagger to inject the singleton repository class into the ViewModel. It is normally best practice to split repositories (or managers) on functionality. UserRepository is responsible for all user related api calls for example.

If you turn this repository into a singleton that you can inject in any ViewModel, any ViewModel now has access to that specific repository.

After quickly looking into Room I found this little snippet (link):

Note: You should follow the singleton design pattern when instantiating an AppDatabase object, as each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances.

This to me means that you can implement the RoomDatabase much in the same way you can use your repository classes. Simply inject them as a singleton into your ViewModel so you don't need to have multiple instances of the same database.

like image 109
Tim Kranen Avatar answered Oct 21 '22 00:10

Tim Kranen