Dagger 2: Component Depends on Multiple Components with Area

I am new to Dagger 2. I am trying to implement it in my Android project. I have a Service that requires GoogleApiClient . I use a dagger to bring it into this service.

 @FragmentScoped @Component(dependencies = {NetComponent.class, RepositoryComponent.class}) public interface CustomServiceComponent { void inject(CustomService customService); } @Singleton @Component(modules = {AppModule.class, NetModule.class}) public interface NetComponent { GoogleApiClient getGoogleApiClient(); } @Singleton @Component(modules = {AppModule.class, RepositoryModule.class}) public interface RepositoryComponent { DatabaseService getDatabaseService(); } 

AppModule , NetModule and RepositoryModule have methods marked by @Singleton @Provides When I create my project, I get this error:

LocationServiceComponent depends on several component areas: @Singleton NetComponent @Singleton RepositoryComponent

I understand that my LocationComponent cannot depend on the two @Singleton components, but I need both to be in my service, and both must be @Singleton .

Is there a better alternative to doing the same?

+6
source share
1 answer

Remember that although you may have several components labeled @Singleton , their life cycles will correspond to the cycles of the class in which you store the component reference.

This means that if you initialize and save your NetComponent and RepositoryComponent in action, it will follow the life cycle of this operation and not really be a singleton application.

Therefore, you probably won't need more than one @Singleton component in an Android app. Consider combining two Singleton components into one component as follows:

 @Component(modules = {AppModule.class, NetModule.class, RepositoryModule.class}) @Singleton public interface AppComponent { GoogleApiClient getGoogleApiClient(); DatabaseService getDatabaseService(); } 

Then, make sure you keep this @Singleton component at the application level and make it available for use in dependent components that are initialized at the fragment or activity level.

 public class MyApp extends Application { private final AppComponent appComponent; @Override public void onCreate() { super.onCreate(); appComponent = DaggerAppComponent.builder() //modules if necessary .build(); } public AppComponent getAppComponent() { return appComponent; } } 

Note that as long as your @FragmentScoped does not have any dependent components, you can still create as many as you want.

Please note that even if one component now introduces GoogleApiClient and DatabaseService , you still get a separation of problems, because they are provided in separate Dagger 2 modules.

+6
source

Source: https://habr.com/ru/post/1012805/


All Articles