I am using Dagger 2.15 with Kotlin. Should I need to add inject line on every Activity? Is it dagger official document updated for using latest version?
AndroidInjection.inject(this)
Should I need to add inject line on every Activity?
No, you don't need it anymore if you extend your activity from DaggerActivity
or from DaggerAppCompatActivity
(if you use the support libraries).
The DaggerActivity is already calling AndroidInjection.inject(this)
as we can see in the source code:
public abstract class DaggerActivity extends Activity implements HasFragmentInjector {
//...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
}
//...
}
Is it dagger official document updated for using latest version?
At today's date the dagger documentation for Android is not updated but...
Application class extending from DaggerApplication
class App : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().application(this).build()
}
}
Simple activity that injects a MainPresenter
class MainActivity : DaggerActivity() {
@Inject lateinit var mPresenter: MainPresenter
//... and the mPresenter is available without anything else
}
The MainPresenter
is provided by the MainModule
@Module
class MainModule {
@Provides
fun provideMainPresenter(context: Context): MainPresenter {
return MainPresenterImpl(context)
}
}
A BuildersModule
is necessary to bind the MainActivity
and other "sub-components"
@Module
abstract class BuildersModule {
@ContributesAndroidInjector(modules = [MainModule::class])
abstract fun bindMainActivity(): MainActivity
}
The AppComponent
now includes our BuildersModule
and a new dagger module called AndroidInjectionModule
or AndroidSupportInjectionModule
(if you use the support libraries).
@Singleton
@Component(modules = [
AndroidInjectionModule::class,
BuildersModule::class
])
interface AppComponent : AndroidInjector<DaggerApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
Notice that we don't define all that inject() functions in this interface anymore.
Gradle dependencies:
// dagger
implementation "com.google.dagger:dagger:2.15"
kapt "com.google.dagger:dagger-compiler:2.15"
// dagger android
implementation "com.google.dagger:dagger-android:2.15"
implementation 'com.google.dagger:dagger-android-support:2.15' // if you use the support libraries
kapt "com.google.dagger:dagger-android-processor:2.15"