5

I read this guide about recommended app architecture for Android. Here is a graphical summery: enter image description here

The role of ViewModel is clear, but I don't understand why we need it if we use Repository. The purpose of ViewModel is to keep the data persistent during the Activity life cycle, but if the Repository anyway exists as long as the process exists, so what advantage is to use also ViewModel? I can make the Repository a singelton and retrieve it's instance directly from the Activity. That way I reduce complexity and achieve the same results.

TNT6
  • 51
  • 1
  • 2
  • 2
    The Repository and the ViewModel have different responsibilities. You can combine them if you like, but I would argue that you are violating the Single Responsibility Principle at that point. It's just a principle, of course, and you're free to violate it if you think your approach is better. – Robert Harvey May 12 '19 at 17:32

3 Answers3

4

If you persist data using a repository, then the changes obviously persist say, a screen rotation. But, the repository instantiation itself does not survive the screen rotation. The view model, however, does, making unnecessary to re load data from the network or a database. Thus, you have at least one advantage: efficiency.

See the view model documentation here.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

2

Yes you can combine them. This mean fewer code and achieve the same result. But for testing and when work in team is better keep them separe. The viewmodel has the responsibility of manage the data from the repository and his representation in the view (activities). The repository give the data to the viewmodel, the real data or mock data for testing proposes, and the view model get it no matter where it from.

Elvis Jr
  • 138
  • 5
0

Very valid question; something I've always been wondering about.

Other than the design recommendations, one reason to persist the data in a ViewModel (and not in the singleton Repository) is that if there are multiple repositories. So in this situation a ViewModel provides a single point of interaction for the UI controllers.

Another reason could be that holding a large amount of data in a Repository throughout the lifecycle of the app might not be desirable. As they say, carrying large global state in singletons is not a recommended practice. On Android, in particular, this could increase the risk of native process being killed due to high memory consumption when the app is in the cached state.

Irfan Latif
  • 101
  • 2