-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Named annotation and qualifiers
Devrath edited this page Oct 6, 2023
·
7 revisions
Contents |
---|
Observations |
Output |
Code |
- The
named annotations
orqualifiers
are used to differentiate between two different values in a single class type that is being injected using the dagger. - One such scenario is say you have an interface and 2 different implementations of the interface, Now you create 2 modules for this interface and then add both the modules in the component you are preparing. This would result in an error since
dagger
doesn't understand which implementation to use. - We can resolve this by specifying a qualifier for this purpose.
OS type is Android
Contents |
---|
Implementations |
Qualifiers |
Modules |
Components |
Activity |
OS.kt
interface OS {
fun getOsType()
}
AndroidOs.kt
class AndroidOs @Inject constructor() : OS {
override fun getOsType() {
printLog("OS type is Android")
}
}
AppleOs.kt
class AppleOs @Inject constructor() : OS {
override fun getOsType() {
PrintUtils.printLog("OS type is IOS")
}
}
MobileOs.kt
class MobileOs @Inject constructor(
@AndroidOsQualifier private val osType : OS
) {
fun displayOSType(){
osType.getOsType()
}
}
AndroidOsQualifier.kt
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class AndroidOsQualifier
IosOsQualifier.kt
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class IosOsQualifier
AndroidOsModule.kt
@Module
@DisableInstallInCheck
class AndroidOsModule {
@AndroidOsQualifier
@Provides
fun providesAndroidOs() : OS {
return AndroidOs()
}
}
IosOsModule.kt
@Module
@DisableInstallInCheck
class IosOsModule {
@IosOsQualifier
@Provides
fun providesAndroidOs() : OS {
return AppleOs()
}
}
OsComponent.kt
@Component(modules = [AndroidOsModule::class,IosOsModule::class])
interface OsComponent {
fun getMobileOs() : MobileOs
}
MyActivity.kt
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityDaggerConceptsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDaggerConceptsBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListener()
}
private fun setOnClickListener() {
binding.apply {
// Using Qualifiers
usingQualifiersId.setOnClickListener {
val comp = DaggerOsComponent.create().getMobileOs()
comp.displayOSType()
}
}
}
}