简体   繁体   中英

How to use Dagger2's subcomponent into GWT

I'm trying to link two component with Dagger2 (version 2.17). One is a kind of GWT activity ( MainView.class ), and the other is a complex widget which embedd some mapping functionnalities ( CarteWidget.class ).

I would like define the activity as a @Component which contains in particular a @Subcomponent to contains CarteWidget's dependencies.

Here my main component and its module:

@Lvl1Scope
@Component(modules = Lvl1Module.class)
public interface Lvl1Component {

    MainView getMainView();

}

@Module(subcomponents = CarteSubComponent.class)
public class MainModule {

    @Provides
    public MainView provideMainView (CarteSubComponent.Builder carteBuilder) {
        return new MainView (carteBuilder.build().getCarte());
    }
}

And my subcomponent and its module:

@CarteScope
@Subcomponent(modules = CarteModule.class)
public interface CarteSubComponent {

    CarteWidget getCarte();

    @Subcomponent.Builder
    interface Builder {

        CarteSubComponent build();
    }

    @Module
    public class CarteModule {

    }

}

It works but I don't like it, I prefered to inject my CarteWidget into my MainView without using a @Provides methode. So my main module only contains the way to get the CarteWidget from the subcomponent:

@Module(subcomponents = CarteSubComponent.class)
public class Lvl1Module {

    @Provides
    public CarteWidget provideCarte(CarteSubComponent.Builder carteBuilder) {
        return carteBuilder.build().getCarte();
    }

}

But with this very small change I got an infinite loop because the provideCarte Lvl1Module 's method is called when carteBuilder.build().getCarte() is executed...

If I add a CarteWidget 's producer method into my subcomponent I got an error that two binding are found for CarteWidget type, that is true.

That I want is my Lvl1Component be able to inject Subcomponent into it's graph, and I want to let the Subcomponent to choose the implementation to use. Is it possible with subcomponent? What did I misunderstand?

Components in Dagger represent "scopes" aka lifecycle. Your MainView depends on CarteWidget , so its lifecycle is (necessarily) longer than that of the widget. That would lead to the view being in a subcomponent and the widget in the parent component, not the reverse (or both in the same component).

If you want isolation, then use component dependencies rather than subcomponents; but you're trying to bind things backwards here.

The real question is: why do you want to use subcomponents, or even separate components?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM