What is the proper way to implement .addCallback() when providing RoomDatabase via Dagger 2?

Answer #1 100 %

I have managed it like this:

class DataModule {

lateinit var trainDB: TrainDB

fun provideDb(app: Application): TrainDB {
    trainDB = Room
            .databaseBuilder(app, TrainDB::class.java, "train.db")
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {




    return trainDB

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.

You’ll also like:

© 2023 CodeForDev.com -