Android – DI – Dagger

Dagger

Dagger is DI library by Square (2 is Google)

This sample is from this page’s idea (Dagger basics)

Preparation

build.gradle

apply plugin: 'kotlin-kapt'

dependencies {

    def dagger_version = "2.27"
    
    api "com.google.dagger:dagger-android:$dagger_version"
    api "com.google.dagger:dagger-android-support:$dagger_version" // if you use the support libraries
    //annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"

    kapt "com.google.dagger:dagger-compiler:$dagger_version"
}

Component

Component makes a graph of dependencies.

Prepare dependency objects under this and are called from inject target.

ApplicationGraph.kt

@Singleton
@Component
interface ApplicationGraph {
    // The return type  of functions inside the component interface is
    // what can be provided from the container
    fun repository() : DataRepository
}

@Singleton indicates this class is singleton. In this time, this class is only one time use and no need to consider multiple instantiates.

DataRepository.kt

Data class (Repository is basically data management class

// @Inject annotated fields will be provided by Dagger

@Singleton
class DataRepository @Inject constructor(
    private val localDataSource: DataLocalDataSource,
    private val remoteDataSource: DataRemoteDataSource
) {

}


class DataLocalDataSource @Inject constructor() {}

class DataRemoteDataSource @Inject constructor() {}

@Inject is managed by dagger.

In this time, it’s simple. No special constructor, just easy to create instance.

Data.kt

data class Data(val name: String)

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Dagger creates DaggerApplicationGraph class
        val applicationGraph : ApplicationGraph = DaggerApplicationGraph.create()
        val dataRepository: DataRepository = applicationGraph.repository()
        val dataRepository2 : DataRepository = applicationGraph.repository() // can create multiple
    }
}

Done. Sometimes, Android Studio cannot understand Dagger generated class, so you need to clean or rebuild project.

Android
スポンサーリンク
Professional Programmer2

コメント