首页 > 解决方案 > 确保 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
        }
    }

标签: androidkotlinandroid-roomkotlin-coroutines

解决方案


推荐阅读