Understanding Advanced Dagger Concepts (Part 2)
Hi, I am Shwetha..A passionate Android application developer -> sharing my journey of learning, building and teaching modern software development. You will find beginner friendly guides, practical breakdowns of real-world Android concepts and honest reflections on tech, productivity and personal growth.
I believe real progress is made one commit, one lesson and one shared experience at a time.
Let’s grow together
Singleton and Lifecycle
Use scopes like @Singleton to ensure only one instance exists through app lifetime.
Dagger Evolution
Dagger was initially built by Square using reflection which is slower comparatively. Next is from, Google’s Dagger 2 generates code at compile time, making apps faster and safer.
Organizing Dagger in Your Project
Create a di folder with:
modules/for classes providing dependencies (@Modulewith@Provides)components/for interfaces connecting providers and consumers annotated with@ComponentFiles with scopes and qualifier annotations
Sample Module
@Module
class EngineModule {
@Provides
fun provideMotor(): Motor = FastMotor()
@Provides
fun provideEngine(motor: Motor): Engine = Engine(motor)
}
Sample Component
kotlin@Singleton
@Component(modules = [EngineModule::class])
interface AppComponent {
fun inject(car: Car)
}
Injection Example
kotlinclass Car @Inject constructor(val engine: Engine) {
fun drive() {
engine.ignite()
println("Car is driving")
}
}
Injection can also be done by fields or methods
Big Bucket vs Small Bucket
Big bucket (Application scope) vs small bucket (Activity/Fragment scope) manage dependency lifetimes differently.
Gradle Dependencies Reminder
implementation "com.google.dagger:dagger:2.xx"
kapt "com.google.dagger:dagger-compiler:2.xx"
dagger-compiler generates code during compile-time via KotlinPoet or JavaPoet, improving performance.
Missed the previous parts of this Dagger series? Start here: