Junior — Middle
What is the main function and application of the Dagger library in Android application development?
sobes.tech AI
Answer from AI
Dagger is a dependency injection library for Android applications. Its main function is to automate the creation and provision of objects that other components depend on, simplifying dependency management and increasing code testability.
Using Dagger allows:
- To avoid manual creation and passing of dependencies.
- To centralize dependency configuration.
- To improve modularity and code readability.
- To facilitate unit testing by enabling dependency substitution.
Example of using Dagger in Android:
@Component
interface AppComponent {
fun inject(activity: MainActivity)
}
class MainActivity : AppCompatActivity() {
@Inject lateinit var repository: UserRepository
override fun onCreate(savedInstanceState: Bundle?) {
DaggerAppComponent.create().inject(this)
super.onCreate(savedInstanceState)
// Now repository is ready to use
}
}
Thus, Dagger helps manage dependencies in the application efficiently and safely.