Late init / dynamic dependency initialisation in Dagger

13 Views Asked by At

I've following scenario:
I have an Activity which performs some initialisation, when this initialisation is offer I'm able to construct a runtimeDependency.

This dependency I needed to create SomeRepository object. Is there a way to initialise this dependency in onCreate? So it could be later used by simply doing following?

 @Inject lateinit var someRepository: SomeRepository

In code it looks like that:
class InitializeActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // some initialization, that waits for status from server
        val runtimeDependency : B = B("I'm runtime dependency")
    }
}

@Reusable
class SomeRepository @Inject constructor(
    private val compileTimeDependency: A, // This is injected OK
    private val runTimeDependency: B
) {

}

class FirstModule(){
    // This won't work because we have no way of providing runTimeDependency
    @Inject lateinit var someRepository: SomeRepository
}

So far it's done by moving runtimeDependency to late init var, and initialising this field manually later. The problem with that approach is that I get sometimes errors that runTimeDependency wasn't initialised. I guess it is caused by the fact that SomeRepository is used in other places as well, and in some scenarios I don't provide this runetimeDependency on time.

@Reusable
class SomeRepository @Inject constructor(
    private val compileTimeDependency: A, // This is injected OK
) {
    private lateinit var runTimeDependency: B
}

Then initializing the missing lateinit var in activity

class InitializeActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        @Inject lateinit var someRepository: SomeRepository

        // some initialization, that waits for status from server
        val runtimeDependency : B = B("I'm runtime dependency")

        someRepository.runTimeDependency = runtimeDependency
    }
}

I've looked into dagger AssistedInject https://funkymuse.dev/posts/assisted-inject-on-steroids/

but it looks like in every place where I do @Inject now I would have to call factory method and provide it with a runTimeDependency. So not something I'm looking for. Because only in activity I can create this runTimeDependency

0

There are 0 best solutions below