How to provide Room Dao dependency using Dagger2 for Android?

Viewed 1241

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?

1 Answers

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
        )
    }
Related