-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Injecting third party classes
Devrath edited this page Oct 6, 2023
·
6 revisions
Contents |
---|
Observations |
Output |
Code |
- Sometimes we come across scenarios where we need to inject third-party objects in the constructor or the field in a project
- We know that the third-party classes are not editable and we cannot modify them. So there is a way we can inject the third-party object using the dagger.
- We use
modules
that dagger provides where we can create the object and return for the@provides
annotation. - We need to make sure, we mention this module in
@Component
annotated array in thecomponent
class. - We can use both
constructor
andfield
injections for this purpose.
Samsung mobile constructor is invoked !
Running samsung mobile !
Contents |
---|
implementations |
Modules |
Components |
Activity |
SamsungRemote.kt
class SamsungRemote {
init { printLog("Samsung mobile constructor is invoked !") }
fun runMobile() { printLog("Running samsung mobile !") }
}
SamsungRemoteModule.kt
@Module
@DisableInstallInCheck
class SamsungRemoteModule {
@Provides
fun provideSamsungRemote(): SamsungRemote {
return SamsungRemote()
}
}
RemoteComponent.kt
@Component(modules = [SamsungRemoteModule::class])
interface RemoteComponent {
fun getMobile() : SamsungRemote
}
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 third party classes
injectingThirdPartyId.setOnClickListener {
val samsungMobileComponent = DaggerRemoteComponent.create().getMobile()
samsungMobileComponent.runMobile()
}
}
}
}