I have a subcomponent that I need to pull something out of:
@Subcomponent(modules = {SubModule.class})
@SubScope
public interface SubComp {
// ...
Thing getThing();
}
Each time #getThing
is called, I need a new instance of Thing
.
Thing
also has its own orbit of items that need to be created with it. Naturally, my instinct is to create another subcomponent for it:
@Subcomponent(modules = {ModuleThing.class})
@ThingScope
public interface SubCompThing {
// ...
}
But here is my dilemma: Which piece of code should actually be creating Thing
?
If I put a provider into SubModule
, I then need to bind that instance into SubCompThing
, but I get a warning about binding multiple instances. The warning is fatal in my build, and actually states that the warning will become an error in the future:
@Module(subcomponents = {SubCompThing.class})
interface SubModule {
@Provides
static providesThing(SubCompThing.Factory thingCompFactory) {
Thing thing = new Thing();
thingComp = thingCompFactory.create(thing); // Warning about duplicate binding.
// Do some stuff with thingComp
return thing;
}
}
If I have SubCompThing
create Thing
directly itself, my warning turns into an error with the same problem:
@Module
interface ModuleThing {
@Provides
@ThingScope
static Thing providesThing() {
return new Thing();
}
}
@Module(subcomponents = {SubCompThing.class})
interface SubModule {
@Provides
static Thing providesThing(SubCompThing.Factory thingCompFactory) {
thingComp = thingCompFactory.create();
// Do some stuff with thingComp
return thingComp.getThing();
}
}
(Dagger compiles that Thing
is bound twice, since there are two providers for it.)
How can I have my top level SubComp
return new Thing
s on demand, and have each of those Thing
s have their own subcomponent instance associated with them?