【发布时间】:2021-12-31 17:48:32
【问题描述】:
我正在阅读 Google 的 data layer guide,在链接的部分中,他们有以下 sn-p:
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>
}
使用 Koin 注入 NewsApi 依赖项非常简单,但是如何使用 Koin 注入 CoroutineDispatcher 实例呢?我使用了 Koin 网站上的搜索功能,但没有任何结果。过滤的 ddg 搜索也不会产生很多结果。
【问题讨论】:
-
类似 This 的东西。这只是一个我现在找不到更好的问题。也阅读 cmets。
-
@ADM 谢谢,链接问题的评论部分中的链接帮助了我。我很快就会发布一个使用命名范围的解决方案!
标签: android kotlin kotlin-coroutines koin