Dagger 2 Flashcards

1
Q

@Component in Dagger?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How is @Inject used in Dagger?

A

For constructor injection: SomeClass @Inject constructor()
For field injection: @Inject lateinit var repo: StoreRepository

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

@Module & @Provides usage?

A

For dependencies Dagger can’t create automatically.

Example:

```kotlin
@Module
class NetworkModule {
@Provides
fun getFeedAPIs(): FeedAPI {
return Retrofit.Builder()…build().create(FeedAPI::class.java)
}
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

When to use @Binds?

A

For interface implementations that need no extra setup.

Example:

```kotlin
@Module
abstract class UserRepoModule {
@Binds
abstract fun getUserRepo(mockRepo: MockRepo): UserRepo
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Difference between @Provides and @Binds?

A

@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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is @Named used in Dagger?

A

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)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is @Qualifier and its difference from @Named?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How are dynamic/runtime dependencies handled in Dagger?

A

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)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is @Singleton in Dagger?

A

Scope annotation ensuring single instance per component.

Example:

```kotlin
@Singleton
@Component
interface AppComponent { … }

@Singleton
class UserRepository @Inject constructor() { … }
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly