简体   繁体   中英

koin pass CoroutineScope as dependency for RoomDatabaseCallback

I have a database which requires a CoroutineScope for initialization.

@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()
  }
}
} 

how to pass my ViewModel in Modules as CoroutineScope?

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

this example from https://github.com/googlecodelabs/android-room-with-a-view/blob/kotlin/app/src/main/java/com/example/android/roomwordssample/WordRoomDatabase.kt they initialized database in ViewModel but I can not do this. I must initialize throw Koin Dependency Injection I spend two days trying and experimenting but without any success.

You also need to declare CoroutineScope in your 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>()) }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM