According to the article below. https://developer.android.com/jetpack/guide/data-layer#network-request
Make a network request 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.
We need a data source class to manage network operations. It's a given example. As you can see API is a parameter of the NewsRemoteDataSource
Class.
class NewsRemoteDataSource(
private val newsApi: NewsApi,
private val ioDispatcher: CoroutineDispatcher
) {
/**
* Fetches the latest news from the network and returns the result.
* This executes on an IO-optimized thread pool, the function is main-safe.
*/
suspend fun fetchLatestNews(): List<ArticleHeadline> =
// Move the execution to an IO-optimized thread since the ApiService
// doesn't support coroutines and makes synchronous requests.
withContext(ioDispatcher) {
newsApi.fetchLatestNews()
}
}
}
// Makes news-related network synchronous requests.
interface NewsApi {
fun fetchLatestNews(): List<ArticleHeadline>
}
However, I found lots of repositories like this. They're not using DataSource class. They're implementing API to the repository directly. According to the article above, android suggests the DataSource
class to handle network operations. Which example is more effective? Which one should I use? What's the difference between them? Why lots of people are using 2nd one?
class CoinRepositoryImpl @Inject constructor(
private val api: CoinPaprikaApi
) : CoinRepository {
override suspend fun getCoins(): List<CoinDto> {
return api.getCoins()
}
override suspend fun getCoinById(coinId: String): CoinDetailDto {
return api.getCoinById(coinId)
}
}