データソースの具体例/Android
データソースの具体例/kotlin
code:kotlin
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>
}
注目したポイント
引数(依存先)
NewsAPI
依存関係を置き換えられるようになる
テストが容易になる
疑似データソースの実装を組み込むことにより実現
CoroutineDispatcher
代替
Executor