Migration to Dagger 2.24 Guide (Android)
Chang-Eric released Dagger 2.24
And there are some deprecations/removals:
dagger.android
'sHas{Activity,Fragment,Service,ContentProvider,BroadcastReceiver}
interfaces are now removed in favor ofHasAndroidInjector
(which can handle any type).HasAndroidInjector
was added in 2.23, and is supported together with the old types in that version.
In this story, I want to show how to replace it
Replace
AppComponent
If you are using AndroidSupportInjectionModule, replace it with AndroidInjectionModule
. You no longer need to use AndroidSupportInjectionModule
@Singleton
@Component(modules = [AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class])
interface AppComponent : AndroidInjector<YourApplication> {override fun inject(instance: YourApplication)@Component.Builder
interface Builder {@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
Application
Replace Has{Activity,Fragment..}, etc. implemented in Application with HasAndroidInjector
class YourApplication: Application(), HasAndroidInjector { @Inject
lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> {
return androidInjector
} override fun onCreate() {
super.onCreate()
DaggerAppComponent.builder()
.application(this)
.build()
.inject(this)
}
}
Until now there was a DispatchingAndroidInjector
for each class for Activity, Fragment, Service, etc., but it is now a single DispatchingAndroidInjector<Any>
Activity, Fragment
Replace Injectors such as HasFragmentAndroidInjector
with HasAndroidInjector
.
class YourActivity : AppCompatActivity(), HasAndroidInjector { @Inject
lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> {
return androidInjector
} // ...
}public class YourFragment extends Fragment {
@Inject SomeDependency someDep; @Override
public void onAttach(Activity activity) {
AndroidSupportInjection.inject(this);
super.onAttach(activity);
// ...
}
}
That’s all :)
If you are an Android Developer, you can check it out my other story:
If you enjoyed reading this article, it would mean a lot if you show your support using the 👏 clapping icon and share with your colleagues and friends.
Thanks and happy coding!