Skip to content

Dagger ‐ Named annotation and qualifiers

Devrath edited this page Oct 6, 2023 · 7 revisions

Observations

  • The named annotations or qualifiers 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.

Output

OS type is Android

Code

Implementations

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()
    }
}

Qualifiers

AndroidOsQualifier.kt

@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class AndroidOsQualifier

IosOsQualifier.kt

@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class IosOsQualifier

Modules

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()
    }
}

Components

OsComponent.kt

@Component(modules = [AndroidOsModule::class,IosOsModule::class])
interface OsComponent {
    fun getMobileOs() : MobileOs
}

Activity

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()
            }

        }
    }
}
Clone this wiki locally