What is the proper way to implement .addCallback() when providing RoomDatabase via Dagger 2?
Answer #1 100 %I have managed it like this:
@Module
class DataModule {
lateinit var trainDB: TrainDB
@Singleton
@Provides
fun provideDb(app: Application): TrainDB {
trainDB = Room
.databaseBuilder(app, TrainDB::class.java, "train.db")
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
/*
trainDB.stationDao().insert(...)
*/
}
})
.build()
return trainDB
}
@Singleton
@Provides
fun providesStationDao(db: TrainDB) : StationDao = db.stationDao()
}
But remember You need to to do a fake read from the database in order to initiate the db and invoke onCreate(). don't write into db as your first interact when db hasn't been created because it will create a race condition and your on create writing won't take effect.