Skip to content

duonghd7/hd-kotlin-di-dagger2

Repository files navigation

Kotlin Dependency Injection With Dagger2

Prepare

  1. Install Android Studio version 3.0.1 or more
  2. Create new android project and check on "Include Kotlin support"

image

I. Compile library

    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"
    }

II. Config

  1. 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
  1. Create files and content flow as
    <application
        ...
        android:name=".MainApplication">
        
        ...
    </application>

III. Use

    @Module
    class ApplicationModule(val app: Application) {
        ...

        @Provides
        @ApplicationScope
        fun providePerson(): Person {
            return Person("Alice", 30)
        }
    }
    @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:

image

SecondActivity:

image

About

Config kotlin dependency injection with dagger2

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages