【发布时间】:2021-10-18 19:35:23
【问题描述】:
我用hilt写了一个数据库创建方法,我想在数据库中预填充一些数据,但是我应该如何在AppModule中写一个RoomDatabase.Callback()?
@Database(entities = [Puzzle::class], version = 1, exportSchema = false)
abstract class PuzzleDatabase : RoomDatabase() {
abstract fun getPuzzleDao() : PuzzleDao
}
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun PuzzleDatabase(
@ApplicationContext app: Context,
scope: CoroutineScope
) = Room.databaseBuilder(
app,
PuzzleDatabase::class.java,
"puzzle_database"
).build()
@Singleton
@Provides
fun getDao(db: PuzzleDatabase) = db.getPuzzleDao()
}
使用 viewModel 创建 RoomDatabase.Callback() 而不使用 hilt 看起来像这样
@Database(
entities = [Puzzle::class], version = 1
)
abstract class PuzzleDatabase : RoomDatabase() {
abstract fun puzzleDao(): PuzzleDao
private class PuzzleDataBaseCallBack(
private val scope: CoroutineScope
): RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
INSTANCE?.let { database ->
scope.launch {
val puzzleDao = database.puzzleDao()
puzzleDao.insert(Puzzle(0, 9L, 5L, Puzzles.TWO))
}
}
}
}
companion object {
@Volatile
private var INSTANCE: PuzzleDatabase? = null
fun getDatabase(
context: Context,
scope: CoroutineScope
): PuzzleDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
PuzzleDatabase::class.java,
"puzzle_database"
)
.addCallback(PuzzleDataBaseCallBack(scope))
.build()
INSTANCE = instance
instance
}
}
}
}
但是在我的 AppModule 中,PuzzleDataBase() 有 @Singleton @Provides 注解,我应该如何正确创建 PuzzleDataBaseCallBack?
【问题讨论】:
标签: android sqlite android-room android-jetpack-compose dagger-hilt