Skip to content

Instantly share code, notes, and snippets.

@gacordeiro
Last active May 14, 2020 01:26
Show Gist options
  • Save gacordeiro/f02762cc9f83e3e96487135d47cd0c33 to your computer and use it in GitHub Desktop.
Save gacordeiro/f02762cc9f83e3e96487135d47cd0c33 to your computer and use it in GitHub Desktop.
Dagger 2.11 initial setup example
Dagger 2.11 initial setup example
compile "com.google.dagger:dagger:2.11",
compile "com.google.dagger:dagger-android-support:2.11",
kapt "com.google.dagger:dagger-android-processor:2.11",
kapt "com.google.dagger:dagger-compiler:2.11",
@Module(
includes = {
ActivitiesBuilder.class, //this you have to create
AndroidInjectionModule.class, //this is imported on dependencies
...
}
)
public class CoreModule { ...}
@Module
abstract class ActivitiesBuilder {
@ContributesAndroidInjector(modules = arrayOf(SomeFeatureModule::class))
abstract fun someFeatureActivity(): SomeFeatureActivity
//For each new activity, just create one more module and put an abstract method here
}
//If you are using MVP or any other architecture that needs a reverence to
//SomeFeatureActivity hidden behind an interface, you can do it in SomeFeatureModule
@Module
class SomeFeatureModule {
@Provides
fun provideView(view: SomeFeatureActivity): SomeFeatureView = view
@Provides
fun providePresenter(view: SomeFeatureView): SomeFeaturePresenter = SomeFeaturePresenter(view)
}
public class MyApplication extends Application implements HasActivityInjector {
@Inject DispatchingAndroidInjector<Activity> activityInjector;
protected CoreComponent coreComponent;
@Override public AndroidInjector<Activity> activityInjector() {
return activityInjector;
}
@Override public void onCreate() {
super.onCreate();
coreComponent = DaggerCoreComponent.builder()
... //init any needed dependencies here
.build()
coreComponent.inject(this); //activityInjector has to be injected here by dagger
}
(...)
}
class SomeFeatureActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this) //this had to be called before super.onCreate
super.onCreate(savedInstanceState)
...
}
}
If you need to inject fragments, you make your activity implement
HasFragmentInjector or HasSupportFragmentInjector similar to what you done on the application
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment