In the Room Database, I need to pass the CoroutineScope so that it runs RoomDatabaseCallback (to initialize the database).
@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 ): WordRoomDatabase { // if the INSTANCE is not null, then return it, // if it is, then create the database return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, WordRoomDatabase::class.java, "word_database" ) // Wipes and rebuilds instead of migrating if no Migration object. // Migration is not part of this codelab. .fallbackToDestructiveMigration() .addCallback(WordDatabaseCallback(scope)) .build() INSTANCE = instance // return instance instance } } private class WordDatabaseCallback( private val scope: CoroutineScope ) : RoomDatabase.Callback() { /** * Override the onOpen method to populate the database. * For this sample, we clear the database every time it is created or opened. */ override fun onOpen(db: SupportSQLiteDatabase) { super.onOpen(db) // If you want to keep the data through app restarts, // comment out the following line. INSTANCE?.let { database -> scope.launch(Dispatchers.IO) { populateDatabase(database.wordDao()) } } } } /** * Populate the database in a new coroutine. * If you want to start with more words, just add them. */ suspend fun populateDatabase(wordDao: WordDao) { // Start the app with a clean database every time. // Not needed if you only populate on creation. wordDao.deleteAll() var word = Word("Hello") wordDao.insert(word) word = Word("World!") wordDao.insert(word) } } }
scope: CoroutineScope
I need to pass as a dependency
val appModule = module { single <Dao>{ WordRoomDatabase.getInstance(get(),**зависимость сюда Mymodel**).wordDao()} single<Repository> { RepositoryImpl(get()) } viewModel { MyModel(get(),get()) }
}
just in case the same question in English https://stackoverflow.com/questions/56183476/koin-pass-coroutinescope-as-dependency-for-roomdatabasecallback