Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 8]

Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 8]

Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)

ยท

2 min read

Assisted Injection with Hilt

Assisted Injection in Hilt is used to inject dependencies into a class with a custom constructor, such as classes generated by third-party libraries or classes that require runtime parameters. Hilt supports assisted injection by generating factories that provide the required dependencies to construct these classes.

To use assisted injection, we need to define a factory interface using the @AssistedInject annotation for the class that requires assisted injection. The factory interface will be automatically generated by Hilt, and we can then use it to create instances of the class with custom parameters.

Example - Assisted Injection with Hilt:

1. Define the class that requires assisted injection:

// The class that requires assisted injection
class MyClass @Inject constructor(
    private val myDependency: MyDependency,
    private val customParameter: String // Assisted injection parameter
    ) {
    // Class implementation
}

2. Define the factory interface using @AssistedInject:

// Factory interface for assisted injection
interface MyClassFactory {
    fun create(customParameter: String): MyClass
}

// Implementation of the factory interface using @AssistedInject
@AssistedInject
class MyClassFactoryImpl @Inject constructor(
    private val myDependency: MyDependency) : MyClassFactory {

    override fun create(customParameter: String): MyClass {
        return MyClass(myDependency, customParameter)
    }
}

3. Use the factory to create instances of MyClass:

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
    @Inject
    lateinit var myClassFactory: MyClassFactory

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        val customParameter = "Hello, Assisted Injection!"
        val myClassInstance = myClassFactory.create(customParameter)

        // Now, we can use myClassInstance as needed
    }
}

In this example, the MyClass requires assisted injection with the customParameter parameter. We define a factory interface MyClassFactory has a create a method to construct instances of MyClass with the custom parameter. The implementation of the factory, MyClassFactoryImpl, uses the @AssistedInject annotation, indicating that assisted injection is required.

In the MyActivity, we inject the MyClassFactory and use it to create instances of MyClass with the customParameter.

Assisted Injection in Hilt provides a clean and straightforward way to handle classes with custom constructors and runtime parameters, allowing us to benefit from Hilt's dependency injection capabilities even in more complex scenarios.

ย