Step #6: Add Our Database to Koin
Usually, a Room database is a singleton. And, since we are using Koin, we can have Koin supply our database to other classes via dependency injection.
In ToDoApp
, add this line to the koinModule
declaration:
single { ToDoDatabase.newInstance(androidContext()) }
This simply invokes our newInstance()
factory function and exposes that instance as a single
object. It uses an androidContext()
function, supplied by Koin, to get the Application
singleton and supply that as a Context
to our newInstance()
factory function.
However, to enable androidContext()
to work in our single()
call, we need to teach Koin about our ToDoApp
object. To that end, modify onCreate()
in ToDoApp
to look like this:
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@ToDoApp)
modules(koinModule)
}
}
Now, our startKoin()
call contains an androidContext()
setter call, where we provide the Context
to use for our androidContext()
call up in koinModule
.
Technically, we could bypass all of this and have our single()
in koinModule
use this
instead of androidContext()
. The downside of that approach is that if we wanted a different Context
in testing, we would be unable to provide it. Basically, Koin allows us to inject the top-level Context
in addition to injecting our own classes.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.