1 min read
Understanding
Dependency
Injection
in Android
Swipe
Swipe
What is
Dependency Injection ?
A technique where one object provides the
dependencies (other objects it needs) of
another object.
Instead of creating
dependencies within a
class, they are passed
from the outside.
Swipe
Why
Dependency Injection?
In Android, activities, fragments, or view models
often depend on other classes for tasks like
network calls or data persistence.
Without DI, dependencies are
created inside the class,
leading to tight coupling,
which makes the code harder
to test, extend, or modify.
Swipe
Dependency Injection
Plays an Major Role
Decouples Code: It separates how objects are
created from how they are used.
Enhances Testability: You can replace real
objects with test ones during testing.
Improves Scalability: Makes it easier to
manage large codebases with multiple
dependencies.
Swipe
Types of
Dependency Injection
There are three common types of Dependency
Injection:
Constructor Injection: Dependencies are
provided through the constructor of the class.
Field Injection: Dependencies are injected
directly into fields (usually with the help of a
framework).
Method Injection: Dependencies are
provided via setter or other methods in the
class.
Swipe
A Simple Example
Without Dependency Injection
Swipe
Here:
1 Main Activity creates the Repository.
2 It passes it to My View Model manually.
3 This tight coupling makes testing harder and
the code less flexible.
Swipe
With Dependency Injection
(Using Hilt)
Dependency injection frameworks like Hilt
automate this process. Here’s how it looks:
1. Add Hilt Dependencies in your build
gradle:
Swipe
2. Annotate the Application Class
Define Your Dependencies
Create a module to provide the dependencies:
Swipe
4. Inject Dependencies into the View Model
5. Inject the View Model into the Activity
Swipe
Key Advantage of Using Hilt:
No Boilerplate Code: Hilt takes care of creating
and providing dependencies.
Scalable: Adding new dependencies becomes
seamless.
Testable: You can easily mock dependencies for
testing.
Optimized for Android: Hilt is tailored to work
efficiently with Android’s unique lifecycle.
Automatic Lifecycle Management: Hilt takes care
of the lifecycle of injected objects. For example, it
automatically destroys and cleans up objects
when an Activity or Fragment is destroyed.
Thank you for
your Attention!