Reputation: 414
I'm trying to learn about clean architecture. I've a question.According to this article
Making a network request is one of the most common tasks an Android app might perform. The News app needs to present the user with the latest news that is fetched from the network. Therefore, the app needs a data source class to manage network operations: NewsRemoteDataSource.To expose the information to the rest of the app, a new repository that handles operations on news data is created: NewsRepository.
https://developer.android.com/jetpack/guide/data-layer#create_the_data_source
I found lots of example like below. Why they are manage network operations in repository class. Android says we should use a DataSource Class. Can you explain which works needs to be done in repository class? Maybe with some examples.
class WordInfoRepositoryImpl(
private val api: DictionaryApi,
private val dao: WordInfoDao
): WordInfoRepository {
override fun getWordInfo(word: String): Flow<Resource<List<WordInfo>>> = flow {
emit(Resource.Loading())
val wordInfos = dao.getWordInfos(word).map { it.toWordInfo() }
emit(Resource.Loading(data = wordInfos))
try {
val remoteWordInfos = api.getWordInfo(word)
dao.deleteWordInfos(remoteWordInfos.map { it.word })
dao.insertWordInfos(remoteWordInfos.map { it.toWordInfoEntity() })
} catch(e: HttpException) {
emit(Resource.Error(
message = "Oops, something went wrong!",
data = wordInfos
))
} catch(e: IOException) {
emit(Resource.Error(
message = "Couldn't reach server, check your internet connection.",
data = wordInfos
))
}
val newWordInfos = dao.getWordInfos(word).map { it.toWordInfo() }
emit(Resource.Success(newWordInfos))
}
}
Upvotes: 1
Views: 1904
Reputation: 2335
Here is a great article explaining the difference between a DAO
and a Repository
. https://www.baeldung.com/java-dao-vs-repository
I would consider the API
as an impromptu DAO
for remote databases.
Since you don't have access to the remote database structure, it will be the closest thing you are going to get to a DAO
.
This Repository
is responsible for collating the two data sources. The DAO
is the local one and the API
is the remote one.
It looks like it retrieves the local data and emits it. It then tries to retrieve the remote data to update the local data. It finally then re-emits the local data.
I think the example you posted falls within the normal responsibilities of a Repository
, as per the article.
Upvotes: 1