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()
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.
source share