Setup Hilt for Android Dependency Injection

Edit Project build.gradle

buildscript {
    dependencies {
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40'
    }
}

Edit Module build.gradle

plugins {
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}


dependencies {
    implementation 'com.google.dagger:hilt-android:2.40'
    kapt 'com.google.dagger:hilt-compiler:2.40'
    implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-beta01'
}

Create Application class

@HiltAndroidAppclass LuaApp : Application() {}

Edit AndroidManifest.xml to include the application class.

<manufest ...>
    <application
        android:name=".LuaApp"
        ...>

    </application>
</manufest>

Instance Factory

Use @Singleton if only single instance is shared across the application.

@Module@InstallIn(SingletonComponent::class)object DataModule {    @Provides    @Singleton    fun provideFirestore(): FirebaseFirestore {        return Firebase.firestore    }    @Provides    @Singleton    fun provideAuth(): FirebaseAuth {        return Firebase.auth    }    @Provides    @Singleton    fun providePlacesClient(@ApplicationContext context: Context): PlacesClient {        Places.initialize(context, BuildConfig.GOOGLE_PLACES_API_KEY)        return Places.createClient(context)    }}

Inject into Activity

@AndroidEntryPointclass MainActivity : ComponentActivity() {    @Inject lateinit var auth: FirebaseAuth}

Inject into ViewModel

@HiltViewModelclass CardViewModel @Inject constructor(    private val db: FirebaseFirestore,    private val auth: FirebaseAuth,    // savedStateHandle: SavedStateHandle    ): ViewModel() {}

I am using Compose Navigation, thus ViewModel for screen is injected via hiltViewModel. Without hiltViewModel, you will bump into the following exception.

Caused by: java.lang.InstantiationException: java.lang.Class<.CardViewModel> has no zero argument constructor
fun CardScreen(    viewModel: CardViewModel = viewModel()) {  }
composable("card") { CardScreen(viewModel = hiltViewModel()) }

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.