Skip to content

Dagger ‐ Injecting values at runtime by component factory

Devrath edited this page Feb 4, 2024 · 6 revisions

Observations

  • Another way of injecting values dynamically is using the component factory.
  • If we use a component factory we explicitly need to specify how the component is being constructed.
  • If any dynamic values are passed, It has to be passed here.

Output

Sending is successfully via Message Service with tag Pikachu

Code

implementations

NotificationService.kt

interface NotificationService {
    fun sendTo(to:String,from:String,subject:String,body:String)
}

EmailService.kt

class EmailService : NotificationService {
    override fun sendTo( to: String, from: String, subject: String, body: String ) {
        PrintUtils.printLog("Sending is successfully via Email Service")
    }
}

MessageService.kt

class MessageService @Inject constructor( private val messageTag:String) : NotificationService {
    override fun sendTo( to: String, from: String, subject: String, body: String ) {
        PrintUtils.printLog("Sending is successfully via Message Service with tag $messageTag")
    }
}

Modules

MessageServiceModule.kt

@Module
@DisableInstallInCheck
class MessageServiceModule {

    @Provides
    fun provideMessageService(messageTag: String) : NotificationService {
        return MessageService(messageTag)
    }

}

Components

MessageServiceComponent.kt

@Component(modules = [MessageServiceModule::class])
interface MessageServiceComponent {

    fun getMainService() : MainService

    @Component.Factory
    interface Factory{
        fun create(
            @BindsInstance messageTag:String
        ) : MessageServiceComponent
    }

}

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 {
            // Injecting values at runtime - Using Component
            injectValAtRuntimeComponentFactoryId.setOnClickListener {
                val comp = DaggerMessageServiceComponent
                    .factory().create("Pikachu").getMainService()
                comp.initiateAction()
            }
        }
    }
}
Clone this wiki locally