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
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?