https://kotlinlang.org logo
Title
f

Florian

10/30/2020, 10:54 AM
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?
@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

gildor

10/30/2020, 11:36 AM
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

Florian

10/31/2020, 9:39 AM
Thank you. What is wrong with doing db operations right here? I don't have a repository
g

gildor

10/31/2020, 11:33 AM
Because you mix your business logic with dependency resolution logic
f

Florian

11/01/2020, 10:39 AM
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:
@Singleton
@Inject
class DatabaseInitializer(@ApplicationScope coroutineScope: CoroutineScope): RoomDatabase.Callback {
    ...
}
my bad, this would be its own class, not inside the module