Example of usage of Dagger.Android and Architecture components
- Create an architecture with savable to
BundleViewModels; - Move
ViewModelinitialization to Dagger2.Android modules; - Totally incapsulate
ViewModelmanagment logic from final Activity/Fragment.
- DaggerArchActivity implements Dagger2.Android contracts
- DaggerArchFragment same features as
DaggerArchActivityhas; - DaggerArchDialogFragment same features as
DaggerArchActivityhas; - DaggerViewModel which provides
Factoryand supports injections viaAndroidInjector; - DaggerSavableViewModel which provides
Factory, supports injections viaAndroidInjectorand acceptsSavedStateHandleas the second argument of constructor; - Creating
Factoryfor eachViewModelprovides some boilerplate code, so there is an AnnotationProcessor for this purpose. Mark class withGenerateFactoryand its constructors withConstructorPriority, if needed. Usage example is here
You can add dagger2-arch-components module as dependency via maven:
repositories {
maven { url 'https://dl.bintray.com/ufkoku/maven/' }
}
dependencies {
def ver_dagger_arch_components = "2.4.0"
implementation "com.ufkoku:dagger2-arch-components:$ver_dagger_arch_components"
//optional if you want to use factories instead of injection to `ViewModel`
compileOnly "com.ufkoku:dagger2-arch-annotations:$ver_dagger_arch_components"
kapt "com.ufkoku:dagger2-arch-processor:$ver_dagger_arch_components"
}
kapt {
correctErrorTypes = true
}