我正在阅读谷歌的数据层指南,在链接段中,它们有以下片段:
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搜索结果也不多。
发布于 2022-01-01 16:35:23
感谢来自评论的@ADM链接,我成功地使用了建议的这里命名的属性。
在我的示例中,首先为IO Dispatcher创建命名属性,然后SubjectsLocalDataSource类使用get(named("IODispatcher"))调用获取其CoroutineDispatcher依赖项,最后,SubjectsRepository使用经典的get()调用获取数据源依赖项。
SubjectsLocalDataSource声明:
class SubjectsLocalDataSource(
private val database: AppDatabase,
private val ioDispatcher: CoroutineDispatcher
)SubjectsRepository声明:
class SubjectsRepository(private val subjectsLocalDataSource: SubjectsLocalDataSource)最后,在我的Koin模块中
single(named("IODispatcher")) {
Dispatchers.IO
}
// Repositories
single { SubjectsRepository(get()) }
// Data sources
single { SubjectsLocalDataSource(get(), get(named("IODispatcher"))) }https://stackoverflow.com/questions/70544552
复制相似问题