Created
June 5, 2022 13:13
-
-
Save shalperin/c285df157c0f730db6f5d5511b4df402 to your computer and use it in GitHub Desktop.
A Hilt module providing a Room database using a RoomDatabase.Callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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