Dagger 2 Flashcards
@Component in Dagger?
Provides dependencies app-wide. Can return dependencies or have dependency consumers.
Example: @Component interface AppComponent { fun getUserPreferences(): SharedPref }
or @Component interface AppComponent { fun inject(feed: FeedFragment) }
How is @Inject used in Dagger?
For constructor injection: SomeClass @Inject constructor()
For field injection: @Inject lateinit var repo: StoreRepository
@Module & @Provides usage?
For dependencies Dagger can’t create automatically.
Example:
```kotlin
@Module
class NetworkModule {
@Provides
fun getFeedAPIs(): FeedAPI {
return Retrofit.Builder()…build().create(FeedAPI::class.java)
}
}
~~~
When to use @Binds?
For interface implementations that need no extra setup.
Example:
```kotlin
@Module
abstract class UserRepoModule {
@Binds
abstract fun getUserRepo(mockRepo: MockRepo): UserRepo
}
~~~
Difference between @Provides and @Binds?
@Provides for complex creation (in regular class), @Binds for simple binding (in abstract class).
Example of @Provides: fun getUserRepo() { return UserRepoImpl(param1, param2) }
vs @Binds: abstract fun bindRepo(impl: RepoImpl): Repo
How is @Named used in Dagger?
To specify which implementation to use.
Example:
```kotlin
@Named(“mock”)
@Binds
abstract fun getMockRepo(mockRepo: MockRepo): UserRepo
class UserVM(@Named(“mock”) private val repo: UserRepo)
~~~
What is @Qualifier and its difference from @Named?
Type-safe alternative to @Named.
Example:
```kotlin
@Qualifier
annotation class MockRepo
@MockRepo
@Binds
abstract fun bindMockRepo(mockRepo: MockRepoImpl): UserRepo
class UserVM(@MockRepo private val repo: UserRepo)
~~~
How are dynamic/runtime dependencies handled in Dagger?
Using @Component.Factory and @BindsInstance.
Example:
```kotlin
@Component.Factory
interface Factory {
fun create(@BindsInstance retryCount: Int): AppComponent
}
// Usage:
DaggerAppComponent.factory().create(retryCount = 3).inject(this)
~~~
What is @Singleton in Dagger?
Scope annotation ensuring single instance per component.
Example:
```kotlin
@Singleton
@Component
interface AppComponent { … }
@Singleton
class UserRepository @Inject constructor() { … }
~~~