Junior — Middle
What is the purpose of dependency injection in Android projects?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in Android projects is used to manage dependencies between objects, which enhances modularity, testability, and ease of maintenance of the code. Instead of creating dependencies inside a class, they are passed from outside, usually through constructors or setters.
For example, if you have a class that depends on a data repository, with DI you can easily replace this repository with a mock object during testing.
Example using Dagger/Hilt:
class UserRepository @Inject constructor(private val apiService: ApiService) {
// ...
}
class UserViewModel @Inject constructor(private val userRepository: UserRepository) : ViewModel() {
// ...
}
Thus, DI simplifies dependency management, promotes loose coupling of components, and makes unit testing easier.