android - 确保 RoomDatabase.Callback 中的协程完成
问题描述
我正在使用 RoomDatabase.Callback 覆盖并调用 OnCreate 以用数据预填充我的 Room 数据库。我如何确保在继续之前完成此操作?我遇到的问题是我不知道 prePopulateDatabase 何时完成,并且它在没有这些必要数据的情况下在代码中继续。
代码是;
private class AppDatabaseCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
INSTANCE?.let { database ->
scope.launch {
val puzzleDao = database.puzzleDao()
prePopulateDatabase(puzzleDao)
}
}
}
private suspend fun prePopulateDatabase(puzzleDao: PuzzleDao) {
val startingData = StartingData()
puzzleDao.insertAllPuzzles(startingData.getStartingPuzzles())
}
}
以及调用它的片段代码;
loadPuzzlesJob = CoroutineScope(Dispatchers.IO).launch {
// this either returns the existing roomdb, or creates it and fills it with the pre-data
val puzzleDao = AppDatabase.getDatabase(requireContext(), CoroutineScope(Dispatchers.IO)).puzzleDao()
// data should now be available
// PROBLEM - this is running before prePopulateDatabase is, so no data is returned
allPuzzles = puzzleDao.getAllPuzzles().toMutableList()
if (allPuzzles.isEmpty()) {
// puzzles not found, send to error screen
errorFound(ErrorType.PuzzlesNotFound)
}
loadPuzzlesJob?.cancelAndJoin()
}
fun getDatabase(context: Context, coroutineScope: CoroutineScope): AppDatabase {
val tempInstance = INSTANCE
if (tempInstance == null) {
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext, AppDatabase::class.java, "mydbname"
).addCallback(AppDatabaseCallback(coroutineScope)).fallbackToDestructiveMigration().build()
INSTANCE = instance
return instance
}
} else {
return tempInstance
}
}
解决方案
推荐阅读
- javascript - 我将如何选择一个随机行然后在 .txt 中将其删除?
- android - InjectPresenter 在带有库 Moxy 的 Activity 中不起作用
- python - 计数 Game Try/Except 并计算用户尝试次数
- stylelint - 过时的 CSS 属性的规则?
- python - Python selenium 不显示表格内容
- java - 我的机器人正在为 1 个请求发送多条消息
- django - 在 Amazon Elastic Beanstalk 上安装 Anaconda 以在 Django 应用程序中使用
- java - 当值以数字开头时,添加 getter 方法会禁止解析
- scala - spark - 在不使用案例类的情况下为 scala 模拟 pyspark asDict()
- android - Kotlin 片段 NullPointerException