【问题标题】:Injecting a CoroutineDispatcher using Koin使用 Koin 注入 CoroutineDispatcher
【发布时间】: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


【解决方案1】:

感谢来自 cmets 的 @ADM 链接,我设法按照建议的 here 使用命名属性。

在我的例子中,我首先为 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"))) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多