I want to insert some initial items into my todo l...
# coroutines
f
I want to insert some initial items into my todo list. Is this the right place for a custom applicationScope or should I use GlobalScope?
Copy code
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
    private lateinit var database: TaskDatabase

    @Provides
    @Singleton
    fun provideDatabase(
        app: Application,
        @ApplicationScope applicationScope: CoroutineScope
    ): TaskDatabase {
        database = Room.databaseBuilder(app, TaskDatabase::class.java, "task_database")
            .fallbackToDestructiveMigration()
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    val dao = database.taskDao()

                    applicationScope.launch {
                        dao.insert(Task("Wash the dishes"))
                        dao.insert(Task("Do the laundry"))
                        dao.insert(Task("Buy groceries"))
                        dao.insert(Task("Call mom"))
                    }
                }
            })
            .build()
        return database
    }

    @Provides
    @Singleton
    fun provideTaskDao(db: TaskDatabase) = db.taskDao()

    @ApplicationScope
    @Provides
    @Singleton
    fun provideApplicationScope() = CoroutineScope(SupervisorJob())
}

@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class ApplicationScope
g
Are you accessing database from DI? 😱
Anyway, even if you move it to repository, and you would like to prevent those operations to be cancelled, and repo is singleton, use global scope, app scope or even repository scope (which anyway becomes global) is fine I would create own scope for repository
f
Thank you. What is wrong with doing db operations right here? I don't have a repository
g
Because you mix your business logic with dependency resolution logic
f
makes sense, thank you
would it be correct if put the initializer part into a separate provides method?
the insert code would still be inside the Dager module tho
like this:
Copy code
@Singleton
@Inject
class DatabaseInitializer(@ApplicationScope coroutineScope: CoroutineScope): RoomDatabase.Callback {
    ...
}
my bad, this would be its own class, not inside the module