My repository passes in a Room Persistence lib. Dao object as a dependency. The problem is Dao is an interface. The most recent suggestion by Google is to do the following:
// Tells Dagger this is a Dagger module
// Because of @Binds, StorageModule needs to be an abstract class
@Module
abstract class StorageModule {
// Makes Dagger provide SharedPreferencesStorage when a Storage type is requested
@Binds
abstract fun provideStorage(storage: SharedPreferencesStorage): Storage
}
In the example above, SharedPreferencesStorage
is a user created implementation of the interface, Storage
. The problem with Room dao dependencies is that the implementation is generated by the library like roomDatabase.getDatabase(context).myDao()
. The most recent Dagger version seems to avoid using the old way of passing in component dependencies through a module constructor. Is there a way to do this using @Subcomponent.Factory
or @Component.Factory
, or is the "old" way the only way to do this for Room dao dependencies?
You could try the following approach:
@Module
class DatabaseModule {
@Provides
fun provideDaoA(db: MyDb): DaoA = db.daoA()
@Provides
fun provideDaoB(db: MyDb): DaoB = db.daoB()
}
class MyRepository @Inject constructor(private val daoA: DaoA) {..}
Another approach from googlesamples :
@JvmStatic
@Singleton
@TasksLocalDataSource
@Provides
fun provideTasksLocalDataSource(
database: ToDoDatabase,
ioDispatcher: CoroutineDispatcher
): TasksDataSource {
return TasksLocalDataSource(
database.taskDao(), ioDispatcher
)
}
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.