Scoped vs. unscoped Dagger dependencies

The code

@Subcomponent(modules = [MainActivityComponent.MainActivityModule::class])
// @PerActivity
interface MainActivityComponent {
fun inject(mainActivity: MainActivity)

@Module
class MainActivityModule(private val mainActivity: MainActivity) {

@Provides
// @PerActivity
fun presenter(catRepository: CatRepository): MainPresenter {
return MainPresenter(catRepository, mainActivity)
}
}
}
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerActivity

Scoped dependencies

private final class MainActivityComponentImpl implements MainActivityComponent {
private Provider<MainPresenter> presenterProvider; // <-- Reference here

private MainActivityComponentImpl(
MainActivityComponent.MainActivityModule mainActivityModuleParam) {

initialize(mainActivityModuleParam);
}

@SuppressWarnings("unchecked")
private void initialize(
final MainActivityComponent.MainActivityModule mainActivityModuleParam) {
this.presenterProvider = DoubleCheck.provider(MainActivityComponent_MainActivityModule_PresenterFactory.create(mainActivityModuleParam, DaggerMyAppComponent.this.catRepositoryProvider));
}

@Override
public void inject(MainActivity mainActivity) {
injectMainActivity(mainActivity);}

private MainActivity injectMainActivity(MainActivity instance) {
MainActivity_MembersInjector.injectPresenter(instance, presenterProvider.get());
return instance;
}
}

Unscoped dependencies

private final class MainActivityComponentImpl implements MainActivityComponent {
private final MainActivityComponent.MainActivityModule mainActivityModule;

private MainActivityComponentImpl(
MainActivityComponent.MainActivityModule mainActivityModuleParam) {
this.mainActivityModule = mainActivityModuleParam;
}

private MainPresenter getMainPresenter() {
return MainActivityComponent_MainActivityModule_PresenterFactory.presenter(mainActivityModule, app.ericn.daggerplain.DaggerMyAppComponent.this.catRepositoryProvider.get());}

@Override
public void inject(MainActivity mainActivity) {
injectMainActivity(mainActivity);}

private MainActivity injectMainActivity(MainActivity instance) {
MainActivity_MembersInjector.injectPresenter(instance, getMainPresenter());
return instance;
}
}

Hiring Android engineer shorturl.at/bivJO Clean coder, walker & biker. Hater of inefficiency

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store