Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency Injection in Android with Hilt

Dependency Injection in Android with Hilt

An introduction about Hilt. We will also cover the importance of Dependency Injection to create a solid and extensible application that scales to large projects.

Manuel Ernesto

August 25, 2020
Tweet

More Decks by Manuel Ernesto

Other Decks in Programming

Transcript

  1. GDG Location • Reduces the boilerplate code • Makes our

    code reusable and clean • Make testing easier • Ease of refactoring DI advantages
  2. GDG Location // No Dependency Injection class Car { private

    val engine = Engine() fun start() {...} }
  3. GDG Location // No Dependency Injection class Car { private

    val engine = Engine() fun start() {...} } fun main() { val car = Car() car.start() }
  4. GDG Location // With Dependency Injection class Car(private val engine:

    Engine) { fun start() {...} } fun main() { val engine = Engine() val car = Car(engine) car.start() }
  5. GDG Location Hilt • Standardize DI in Android • Build

    on top of Dagger • Tooling Support • AndroidX Extensions
  6. GDG Location Setup buildscript { ... dependencies { ... classpath

    'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha' } } build.gradle (project)
  7. GDG Location Setup apply plugin: 'kotlin-kapt' apply plugin: 'dagger.hilt.android.plugin' //...

    dependencies { implementation "com.google.dagger:hilt-android:2.28-alpha" kapt "com.google.dagger:hilt-android-compiler:2.28-alpha" } build.gradle (app)
  8. GDG Location class Car @Inject constructor() { fun start() {

    } } @AndroidEntryPoint class CarActivity: AppCompatActivity(){ }
  9. GDG Location class Car @Inject constructor() { fun start() {

    } } @AndroidEntryPoint class CarActivity: AppCompatActivity(){ @Inject lateinit var car: Car }
  10. GDG Location class Car @Inject constructor() { fun start() {

    } } @AndroidEntryPoint class CarActivity: AppCompatActivity(){ @Inject lateinit var car: Car override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) car.start() } }
  11. GDG Location AndroidX Extensions class CarViewModel @ViewModelInject constructor( private val

    db: CarDB ) : ViewModel() { ... } @AndroidEntryPoint class CarActivity0 : AppCompatActivity() { val viewModel: CarViewModel by ViewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.start() } }
  12. GDG Location Resources • Using Hilt in your Android app

    [https://cutt.ly/3fsTeno] • Migrating your Dagger app to Hilt [https://cutt.ly/1fsTiU7]