5

我有一个需要 CoroutineScope 进行初始化的数据库。

@Database(entities = [Word::class], version = 1)
 abstract class WordRoomDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao

 companion object {
@Volatile
private var INSTANCE: WordRoomDatabase? = null

fun getDatabase(
        context: Context,
        scope: CoroutineScope//this dependecy!!!
): WordRoomDatabase {
    return INSTANCE ?: synchronized(this) {
        val instance = Room.databaseBuilder(
                context.applicationContext,
                WordRoomDatabase::class.java,
                "word_database"
        )
                .addCallback(WordDatabaseCallback(scope))
                .build()
        INSTANCE = instance
        instance
    }
}

private class WordDatabaseCallback(
        private val scope: CoroutineScope
) : RoomDatabase.Callback() {
    override fun onOpen(db: SupportSQLiteDatabase) {
        super.onOpen(db)
        INSTANCE?.let { database ->
            scope.launch(Dispatchers.IO) {
                populateDatabase(database.wordDao())
            }
        }
    }
}
  suspend fun populateDatabase(wordDao: WordDao) {
    wordDao.deleteAll()
  }
}
} 

如何将模块中的 ViewModel 作为 CoroutineScope 传递?

val appModule = module {
  single <Dao>{ WordRoomDatabase.getInstance(get(),**dependency here
  Mymodel**).wordDao()}
  viewModel { MyModel(get(),get()) }
}

这个例子来自 https://github.com/googlecodelabs/android-room-with-a-view/blob/kotlin/app/src/main/java/com/example/android/roomwordssample/WordRoomDatabase.kt 他们初始化数据库ViewModel 但我不能这样做。我必须初始化 throw Koin Dependency Injection 我花了两天时间尝试和试验,但没有任何成功。

4

1 回答 1

2

您还需要CoroutineScope在您的appModule

val appModule = module {
  single <Dao>{ WordRoomDatabase.getInstance(get(),**dependency here
  Mymodel**).wordDao()}
  viewModel { MyModel(get(),get()) }

  factory { SupervisiorJob() }
  factory { CoroutineScope(Dispatchers.IO + get<SupervisorJob>()) }

}
于 2019-07-03T16:37:11.120 回答