-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Injecting values at runtime by component factory
Devrath edited this page Feb 4, 2024
·
6 revisions
Contents |
---|
Observations |
Output |
Code |
- 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.
Sending is successfully via Message Service with tag Pikachu
Contents |
---|
implementations |
Modules |
Components |
Activity |
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")
}
}
MessageServiceModule.kt
@Module
@DisableInstallInCheck
class MessageServiceModule {
@Provides
fun provideMessageService(messageTag: String) : NotificationService {
return MessageService(messageTag)
}
}
MessageServiceComponent.kt
@Component(modules = [MessageServiceModule::class])
interface MessageServiceComponent {
fun getMainService() : MainService
@Component.Factory
interface Factory{
fun create(
@BindsInstance messageTag:String
) : MessageServiceComponent
}
}
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()
}
}
}
}