dimsuz
12/16/2022, 11:37 AMinterface A
interface B
class AB : A, B
And I want to have a single intance of AB
provided as A
and B
separately:
@Provides fun providesA(): A
@Provides fun providesB(): B
How is this normally done in dagger? Do I do it like this:
@Provides fun providesAB(): AB
@Provides fun providesA(ab: AB): A = ab
@Provides fun providesB(ab: AB): B = ab
Feels like there could be a way to avoid manually writing such basic methods.
Also don't like the fact that I have to provide AB
too, although I'd prefer it to be an implemenation detailNicholas Doglio
12/16/2022, 1:20 PM@Inject
annotation on its constructor and use @Binds
annotation instead of provides.
It should look something like this (sorry on mobile if formatting is weird)
class AB @Inject constructor(): A,B
In your module
@Binds fun bindA(impl: AB) A
@Binds fun bindB(impl: AB): B
Nicholas Doglio
12/16/2022, 1:21 PM@ContributesBinding
annotation can bind an implementation to multiple interfacesNicholas Doglio
12/16/2022, 1:23 PM@Singleton
annotation then AB would look like this
@Singleton class AB @Inject constructor(): A,B
dimsuz
12/16/2022, 1:38 PMdimsuz
12/16/2022, 1:53 PM@ContributesBinding
, because this class is provided using this pattern in several distinct anvil scopes, in different modulesNicholas Doglio
12/16/2022, 2:14 PM@ContributesBinding(AppScope::class, boundType = A::class)
@ContributesBinding(AppScope::class, boundType = B::class)
@ContributesBinding(OtherScope::class, boundType = A::class)
@ContributesBinding(OtherScope::class, boundType = B::class)
@Singleton
class AB @Inject constructor(): A, B
But I'm not sure your module structure so maybe this isn't possible 🤷♀️dimsuz
12/16/2022, 4:51 PMmattinger
12/22/2022, 4:34 AM@Retention(BINARY)
@Qualifier
private annotation class InternalApi
@Module
object MyModule {
@Provides
@InternalApi
fun providesAB(): AB = ....
@Provides fun providesA(@InternalApi ab: AB): A = ab
@Provides fun providesB(@InternalApi ab: AB): B = ab
}
It's sort of a party trick. You're creating a qualifier for the actual instance of AB. However, no one will be able to inject that instance of AB because they won't be able to see the qualifier because it's private to this particular file.mattinger
12/22/2022, 4:44 AMdimsuz
12/22/2022, 12:20 PMmattinger
12/22/2022, 2:01 PM