Home > Software design >  Injecting a CoroutineDispatcher using Koin
Injecting a CoroutineDispatcher using Koin

Time:01-03

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.

CodePudding user response:

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"))) }
  • Related