Skip to content

Instantly share code, notes, and snippets.

@shalperin
Created June 5, 2022 13:13
Show Gist options
  • Save shalperin/c285df157c0f730db6f5d5511b4df402 to your computer and use it in GitHub Desktop.
Save shalperin/c285df157c0f730db6f5d5511b4df402 to your computer and use it in GitHub Desktop.
A Hilt module providing a Room database using a RoomDatabase.Callback
@InstallIn(SingletonComponent::class)
@Module
object DatabaseModule {
@Singleton
@Provides
fun provideTeaDao(database: AppDatabase):TeaDao = database.teaDao()
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext appContext: Context,
/*
This is kind of cool.. You can't pass in teaDao directly, bc that
would be a circular dependency. By passing the Provider, you can
call its get() method _after_ .build() has been executed, i.e. in the
callback. I guess Hilt knows how to inject the Provider from the
provideTeaDao function above.
*/
provider: Provider<TeaDao>
): AppDatabase {
return Room.databaseBuilder(
appContext,
AppDatabase::class.java,
"app_database")
.addCallback(StartingTeas(appContext, provider))
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment