The Repository Pattern

//This code is thought as pseudocode 
fun getClients(): List<Clients> {
val clients = database.getClientsFromDatabase()
if(clients.isEmpty()) {
val clientsFromServer = server.getClientsFromServer()
database.saveClients(clientsFromServer)
return clientsFromServer
} else {
return clients
}
}
Note: We are just explaining Repository so we are referencing it from ViewModel directly. In other approaches like Clean Architecture the Repository would be referenced by UseCases.
fun getClients(): List<Clients> { 
val clients = database.getClientsFromDatabase()
if(clients.isEmpty() || isClientsUpdateNecessary()) {
val clientsFromServer = server.getClientsFromServer()
database.saveClients(clientsFromServer)
return clientsFromServer
} else {
return clients
}
}
  • Single Responsibility: We can separate the responsibility of selecting source from the data consulting. If we want to follow SOLID principles this pattern is a must.
  • Loose coupling: If we have to change the behavior of the way we select the source we don’t need to change the ViewModel. Just changing Repository Implementation will do the thing. ViewModel will use the data the same way.
  • Testability: We are able to test better our code having the data access separately.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store