Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

462
Visualizações
Injecting a CoroutineDispatcher using Koin

I was reading the data layer guide by Google and in the linked segment, they have the following snippet:

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>
}

Injecting the NewsApi dependency using Koin is pretty straightforward, but how can I inject a CoroutineDispatcher instance using Koin? I used the search functionality on Koin's website but nothing came up. A filtered ddg search doesn't yield many results either.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Thanks to @ADM's link from the comments, I managed to use a named property as suggested here.

In my case, I first create the named property for the IO Dispatcher, then the SubjectsLocalDataSource class gets its CoroutineDispatcher dependency using the get(named("IODispatcher")) call and finally, the SubjectsRepository gets its data source dependency using the classic get() call.

SubjectsLocalDataSource declaration:

class SubjectsLocalDataSource(
    private val database: AppDatabase,
    private val ioDispatcher: CoroutineDispatcher
)

SubjectsRepository declaration:

class SubjectsRepository(private val subjectsLocalDataSource: SubjectsLocalDataSource)

and finally, in my Koin module:

single(named("IODispatcher")) {
    Dispatchers.IO
}

// Repositories
single { SubjectsRepository(get()) }

// Data sources
single { SubjectsLocalDataSource(get(), get(named("IODispatcher"))) }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda