Repository in Android’s MVVM architecture

What is Repository in Android’s MVVM architecture?

Repository is a class which purpose is to provide a clean API for accessing data. What that means is that the Repository can gather data from different data sources(different REST APIs, cache, local database storage) and it provides this data to the rest of the app. The other components don’t know where the data comes from, they just consume it. It also serves as a single source of truth. Its role is to keep the local database up to date with the newest fetched data from remote service so that the application can still provide its functionalities with bad Internet connection or no connection at all.
Let’s look at an example where the ViewModel asks the Repository for data which will be visualized in the View.
As we can see the Repository serves as a mediator between the ViewModel and the sources of data. The process of returning data is shown in the diagram.
First the ViewModel asks the Repository for data. The Repository checks what’s in the database and returns the persisted data to the ViewModel for further visualization in the View. While the Repository is getting data from the database, it also sends a request to the remote service in parallel (asynchronously). When the response is back, the Repository updates the database with the newest fetched data. Then this data is consumed from the ViewModel which transforms it in an appropriate way and returns it to the View.
Share :
Share :

Weitere Beiträge

LiveData

LiveData is an observable data holder class. It is also lifecycle-aware, which means that it respects the lifecycle of the other app components, such as activities, fragments and services. It notifies only active observers, represented by the Observer class.

Weiterlesen »