How to use Dependency Injection in an Android app?

Dependency Injection (DI) is a design pattern used to improve the code structure and make it more modular and testable in Android applications. It helps in managing dependencies between classes, allowing for better code management and easier unit testing.

In Android, you can implement Dependency Injection using various frameworks such as Dagger, Hilt, or Koin. Below, we will demonstrate a simple example using Hilt, a popular DI framework for Android.

// Step 1: Add Hilt dependencies in your build.gradle file dependencies { implementation 'com.google.dagger:hilt-android:2.x' kapt 'com.google.dagger:hilt-compiler:2.x' } // Step 2: Apply the Hilt plugin apply plugin: 'dagger.hilt.android.plugin' // Step 3: Create an Application class @HiltAndroidApp class MyApplication : Application() // Step 4: Create a module to provide dependencies @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl("https://api.example.com") .addConverterFactory(GsonConverterFactory.create()) .build() } } // Step 5: Inject dependencies into an Activity @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var retrofit: Retrofit override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Use the injected retrofit instance } }

Dependency Injection Android Hilt Dagger Modular Code Testable Code