- Install Android Studio version 3.0.1 or more
- Create new android project and check on "Include Kotlin support"
- build.gradle module app
apply plugin: "kotlin-kapt"
def dagger = 2.24
def daggerCompiler = 2.24
kapt {
generateStubs = true
}
dependencies {
...
implementation "com.google.dagger:dagger:$dagger"
implementation "com.google.dagger:dagger-android:$dagger"
kapt "com.google.dagger:dagger-compiler:$daggerCompiler"
kapt "com.google.dagger:dagger-android-processor:$daggerCompiler"
}
- Create folder and files folow structure
PACKAGE
|-- domain
|-- home
|-- HomeActivity.kt
|-- HomeComponent.kt
|-- second
|-- SecondActivity.kt
|-- SecondComponent.kt
|-- infrastructures
|-- model
|-- Person.kt
|-- module
|-- ActivityModule.kt
|-- ApplicationComponent.kt
|-- ApplicationModule.kt
|-- scope
|-- ActivityScope.kt
|-- ApplicationScope.kt
|-- MainApplication.kt
- Create files and content flow as
- ApplicationScope.kt
- ActivityScope.kt
- ApplicationModule.kt
- ApplicationComponent.kt
- ActivityModule.kt
- Person.kt
- HomeActivity.kt
- HomeComponent.kt
- SecondActivity.kt
- SecondComponent.kt
- MainApplication.kt
- AndroidManifest.xml
<application
...
android:name=".MainApplication">
...
</application>
- In ApplicationModule, create Person for app
@Module
class ApplicationModule(val app: Application) {
...
@Provides
@ApplicationScope
fun providePerson(): Person {
return Person("Alice", 30)
}
}
- In ApplicationComponent provide resources created by ApplicationModule
@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun person(): Person
}
- In each activity will inject to use without create new Person
@Inject lateinit var person: Person
HomeActivity:
SecondActivity: