This talk was about Dependency Injection with Hilt at DevFest Egypt. First I explained the concept of Dependency Injection without libraries. Next, I showed how to incorporate Hilt into a new app and how to migrate an existing app.
What is Dependency Injection? “dependency injection is a technique in which an object receives other objects that it depends on” According to good ol’ wikipedia
Dependency Injection - Constructor class RoboGardener(private val waterSource: WaterSource) { fun waterPlant() { waterSource.dispenseWater() } } fun main() { val roboGardener = RoboGardener(CupOfWater()) roboGardener.waterPlant() }
class RoboGardener { fun waterPlant() { val waterSource = ServiceLocator.getInstance.findWaterSource() waterSource.dispenseWater() } } Service Locators
@AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var imageLoader: ImageLoader private val viewModel: HiltSampleViewModel by viewModels() ... @AndroidEntryPoint
@AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var imageLoader: ImageLoader private val viewModel: HiltSampleViewModel by viewModels() ...
Multi-module apps - Feature modules “Hilt cannot process annotations in feature modules. You must use Dagger to perform dependency injection in your feature modules” Hilt + Dagger
Multi-module apps - Feature modules 1. Install an Entry Point in the Application Component from the app module @EntryPoint @InstallIn(ApplicationComponent::class) interface ImageFeatureModule { fun imageLoader(): ImageLoader }
Multi-module apps - Feature modules 3. Inject the dependency in the feature module class ImageFeatureModuleActivity : AppCompatActivity() { @Inject lateinit var imageLoader: ImageLoader @AndroidEntryPoint
Resources ● Dependency injection with Hilt ● Dagger Hilt ● Using Hilt in your Android app Codelab ● Migrating your Dagger app to Hilt Codelab ● Scoping in Android and Hilt. Scoping an object A to another object B… | by Manuel Vivo | Android Developers ● Hilt in multi-module apps ● https://github.com/moyheen/HiltSampleApplication ● Image by Gerd Altmann from Pixabay