Android/kotlin/Dagger2
提供: 初心者エンジニアの簡易メモ
dagger2とは
Google製のDIライブラリ
サンプル
dagger2を使って、ざっくりageを取得する方法
app/build.gradle
apply plugin: 'kotlin-kapt' dependencies { def dagger_version = 2.27 implementation "com.google.dagger:dagger:$dagger_version" annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version" kapt "com.google.dagger:dagger-compiler:$dagger_version" kaptTest "com.google.dagger:dagger-compiler:$dagger_version" }
MainActivity.kt
<pre> package com.example.daggerapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import javax.inject.Inject class MainActivity : AppCompatActivity() { @Inject lateinit var viewModel: MainViewModel private val component = DaggerMainActivityComponent.builder() .viewModelModule(ViewModelModule()) .repositoryModule(RepositoryModule()) .build() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) component.inject(this) Log.i("MainActivity", "age=" + viewModel.age()) } }
MainActivityComponent.kt
package com.example.daggerapplication import dagger.Component @Component(modules = [ViewModelModule::class, RepositoryModule::class]) interface MainActivityComponent { fun inject(activity: MainActivity) }
MainViewModel.kt
package com.example.daggerapplication import javax.inject.Inject class MainViewModel @Inject constructor(private val userRepository: IUserRepository) { fun age(): Int { return userRepository.age() } }
RepositoryModule.kt
package com.example.daggerapplication import dagger.Module import dagger.Provides @Module class RepositoryModule { @Provides fun provideUserRepository(): IUserRepository { return UserRepository() } }
UserRepository.kt
package com.example.daggerapplication class UserRepository : IUserRepository { override fun age(): Int { return 12 } }
IUserRepository.kt
package com.example.daggerapplication interface IUserRepository { fun age(): Int }
ViewModelModule.kt
package com.example.daggerapplication import dagger.Module import dagger.Provides @Module class ViewModelModule { @Provides fun provideMainViewModel(userRepository: IUserRepository): MainViewModel { return MainViewModel(userRepository) } }