News Repository
Learn about the repository pattern and how it contributes to the MVVM architecture.
Introduction to repository pattern
In an Android application, the MVVM architecture pattern facilitates the separation of concerns by structuring different components based on their respective duties and responsibilities.
The repository pattern allows us to decouple our application’s business logic and data access layer by entrusting it with the responsibility of managing all local and remote data and delivering it to the business logic.
Repository
The repository’s purpose is to provide a clean API for our application to access data from the local database or REST API. Because the other components are unaware of where the data is coming from, the repository acts as a single source of truth (SSOT) of data for the application. This means it keeps the local database up to date with the most recent information so that it can be loaded when the user has a slow or no internet connection.
Benefits of using repository pattern
- Since the data access logic and business logic are separated, testing is easy.
- The code is clean, maintainable, and reusable.
- It hides the details of how data is stored and accessed from the data store, creating a layer of abstraction.
Cache
The cache is previously viewed or loaded data that’s typically stored locally in our application’s data store in key-value pairs or through the Room
database as a local storage unit. Most applications we deal with or develop usually load data from the internet, and for a better user experience, this data is made available when there’s no internet connection.This feature is made possible with the repository pattern.
The flowchart depicts how data is handled by the repository, along with an explanation.
The chart clearly depicts how data flows in our application from the repository to the ViewModel and into the UI.
Example code
Let’s look at some code to get a better understanding of the repository pattern and how to use it. Different applications will present their repositories in different ways depending on the size, complexity level, and amount of data the application handles. Some will use dependency injections while others won’t, so let’s look at some examples.
class BookRepository {suspend fun getBooks() = NetworkCall.provideMovies.getBooks();}
The above code snippet is from our books application. It receives data directly from our API to the UI via an instance of Retrofit
we created, the repository calls the interface directly to access its abstract methods and will later provide them to the ViewModel to be implemented inside a coroutine. In this application, the repository is strategically introduced for abstraction and to act as a mediator between the data layer and the ViewModel.