dimanche 19 décembre 2021

How to deal with heterogeneous data sources in repository pattern?

Suppose you want to implement a repository patter for handling the data of the app. Imaging you have two Data Sources:

  1. Local cache (or database)
  2. Remote service (Rest API)

The service doesn't allow to make changes, but just to retrieve data, so a very simple interface for the data source could be

interface DataSource {
   suspend fun getClients(): Result<List<Client>> 
   suspend fun getClient(): Result<Client>
}

Both remoteDataSource and cacheDataSource will implement it.

However, the cacheDataSource needs to be filled with the data, so it would need an extra function, something like suspend fun addClients(clients: List<Client>), so I could be change the interface into:

interface DataSource {
   suspend fun getClients(): Result<List<Client>> 
   suspend fun getClient(): Result<Client>
   suspend fun addClients(clients: List<Client>)
}

This however would be bad, as the remoteDataSource will not implement addClients.

So I could remove that function from that interface and make cacheDataSource to implement another interface:

interface CacheClients {
   suspend fun cacheData(clients: List<Client>)
} 

The problem is now that my repository, which should just receive two instances of DataSource, wouldn't know about the other interface that the cacheDataSource is implementing.

What do you think is the best approach in this situation?

Aucun commentaire:

Enregistrer un commentaire