App Startup 🚀 + Hilt 🗡
Combining the two newest libraries from Jetpack to provide dependencies to Initializers
Initializing app start is an unexpectedly complex problem. I have already briefly raised the subject here:
I will address how the new App Startup library from Google’s Jetpack handles (or doesn’t handle 😉) the problem in a different blog post. This one simply describes how to bind App Startup with Hilt.
All the sample code is available here:
Step 1: Hilt dependencies
For the most up to date version follow the official guidelines for setting up Hilt dependencies.
Right now (when the 2.28-alpha
is the newest version available) the setup is as follows:
- In your project’s root
build.gradle
file:
2. In your app/build.gradle
file:
Step 2: App Startup dependency
For the most up to date version follow the official guidelines for setting up App Startup library.
Right now (when the 1.0.0-alpha01
is the newest version available) setting up simply means adding this dependency:
implementation "androidx.startup:startup-runtime:1.0.0-alpha01"
Step 3: Set up Application
This means all the usual stuff:
- Create a class that extends
Application
. - Add it in your
AndroidManifest.xml
(under theandroid:name
parameter in theapplication
tag) - And most importantly: mark it with the new annotation
@HiltAndroidApp
@HiltAndroidApp
class HiltApplication : Application()
Step 4: Create Hilt EntryPoint for Initializers
Initializers
from the App Startup library are components that are not known to the Hilt library, so you need to create a custom EntryPoint
for the library:
Step 5: Set up Graph Dependency Initializer
Truth be told, this step is optional. ApplicationComponent
is initialized by Hilt
library lazily in the Application class. It happens on the first access to the component or in the onCreate
callback.
TLDR: this is not mandatory, but makes things well organized (other Initializers
depend on the DependencyGraphInitializer
).
Step 6: Set up your Initializers that depend on Hilt dependencies
- Create your
Initializer
class:
As you can see it depends on the DependencyGraphInitializer
so it will be created after it.
2. Add an inject
method in the EntryPoint
:
3. Register the Initializer
in the AndroidManifest:
Side note to Google devs: registering in AndroidManifest should be happening automatically… Can’t we simply have a plugin or something that will generate those records for all Initializer
classes?