Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

461
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!