Skip to content

Dagger ‐ Injecting third party classes

Devrath edited this page Oct 6, 2023 · 6 revisions

Observations

  • 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 the component class.
  • We can use both constructor and field injections for this purpose.

Output

Samsung mobile constructor is invoked !
Running samsung mobile !

Code

implementations

SamsungRemote.kt

class SamsungRemote {

    init { printLog("Samsung mobile constructor is invoked !") }

    fun runMobile() { printLog("Running samsung mobile !") }

}

Modules

SamsungRemoteModule.kt

@Module
@DisableInstallInCheck
class SamsungRemoteModule {
    @Provides
    fun provideSamsungRemote(): SamsungRemote {
        return SamsungRemote()
    }
}

Components

RemoteComponent.kt

@Component(modules = [SamsungRemoteModule::class])
interface RemoteComponent {

    fun getMobile() : SamsungRemote

}

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 third party classes
            injectingThirdPartyId.setOnClickListener {
                val samsungMobileComponent = DaggerRemoteComponent.create().getMobile()
                samsungMobileComponent.runMobile()
            }
        }
    }
}
Clone this wiki locally