Skip to content

Instantly share code, notes, and snippets.

@mrolcsi
Last active July 5, 2021 00:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrolcsi/e333f95642026d4e8c8dde0c8509be76 to your computer and use it in GitHub Desktop.
Save mrolcsi/e333f95642026d4e8c8dde0c8509be76 to your computer and use it in GitHub Desktop.
Dagger 2 cheatsheet
@Module
abstract class ActivitiesModule {
@ContributesAndroidInjector(modules = [MainActivityModule::class])
abstract fun contributeMainActivity(): MainActivity
// Other activities come here, same as above.
}
dependencies {
// Dagger 2
implementation 'com.google.dagger:dagger:2.22.1'
kapt 'com.google.dagger:dagger-compiler:2.22.1'
implementation 'com.google.dagger:dagger-android:2.22.1'
implementation 'com.google.dagger:dagger-android-support:2.22.1'
kapt 'com.google.dagger:dagger-android-processor:2.22.1'
}
@Component(
modules = [
AndroidSupportInjectionModule::class,
ActivitiesModule::class,
FragmentsModule::class
// Other modules here.
]
)
@Singleton
interface ApplicationComponent : AndroidInjector<MyApplication> {
interface Factory : AndroidInjector.Factory<MyApplication>
}
@Module
abstract class FragmentsModule {
@ContributesAndroidInjector(modules = [MyFragmentModule::class])
abstract fun contributeMyFragment(): MyFragment
// Other fragments come here, same as above
}
class MyApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerApplicationComponent.builder().build()
}
}
@Module
class MyFragmentModule {
@Suppress("UNCHECKED_CAST")
@Provides
fun provideMyViewModel(fragment: MyFragment, provider: Provider<MyViewModelImpl>): MyViewModel {
return ViewModelProviders.of(fragment, object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = provider.get() as T
}).get(MyViewModelImpl::class.java)
}
// Other @Provides functions here.
}
interface MyViewModel {
// Stuff needed by the UI.
}
class MyViewModelImpl @Inject constructor(private val dependency: Dependency): ViewModel(), MyViewModel {
// ViewModel related stuff. (LiveData, etc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment