Joan Colmenero
07/06/2019, 7:14 PM@Database(entities = [Something::class], version = 1, exportSchema = false)
abstract class MyDatabase : RoomDatabase() {
abstract fun myDao(): MyDao
companion object {
@Volatile
private var INSTANCE: MyDatabase? = null
fun getInstance(context: Context): MyDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
MyDatabase::class.java, "sample_db"
)
.allowMainThreadQueries()
.build()
}
}
salomonbrys
07/06/2019, 7:23 PMstreetsofboston
07/06/2019, 7:25 PMMyDatabase
or BrewDatabase
? Let's assume it is BrewDatabase
.
Remove the companion object
stuff.
Then have a module with a binding, or just a binding, that is something like this
bind<BrewDatabase>() with singleton { Room.databaseBuilder(instance(), BrewDatabase::class.java, "sample_db").allowMainThreadQueries().build() }
Joan Colmenero
07/06/2019, 7:34 PMAll the rest is annotation driven and kodein, or any other DI/SL, cannot help here
streetsofboston
07/06/2019, 7:39 PMJoan Colmenero
07/06/2019, 7:41 PMMyDatabase.getInstance(this).myDao()
streetsofboston
07/06/2019, 7:42 PMval myDb: MyDatabase by kodein.instance()
just like any other kodein dependencymyDb.myDao()
etcJoan Colmenero
07/06/2019, 7:45 PMstreetsofboston
07/06/2019, 7:45 PMJoan Colmenero
07/06/2019, 7:46 PMstreetsofboston
07/06/2019, 7:49 PMJoan Colmenero
07/06/2019, 7:50 PMval contextModule = Kodein.Module("contextModule") {
bind<Context>() with instance()
}
streetsofboston
07/06/2019, 7:59 PMbind<MyApplication> with singleton { MyApplication.INSTANCE }
And MyApplication is your Application subclass, which is a Context subclass as well. Be sure to get the dependency (in your Database Module) using instance<MyApplication>()
though.Joan Colmenero
07/06/2019, 7:59 PMromainbsl
07/09/2019, 7:35 AM// Binding
bind<Database>() with factory { ctx -> Room.databaseBuilder(ctx) }
// Retrieving
val db: Database by kodein.instance(arg = context)