Kristian
Kristian

Reputation: 133

wait till lateinit is assigned

I have a simple class which I use for dependency injection:

class ViewModelFactory( application: Application ) : ViewModelProvider.Factory
{

    val mainFlow                  = MainFlow()
    private val authorizationFlow = AuthorizationFlow()

    init
    {
        mainFlow.authFlow = authorizationFlow
    }

    ..
}

The main flow class:

class MainFlow
{
    lateinit var authFlow : AuthorizationFlow

    init
    {
        if( ::authFlow.isInitialized )
            authFlow.start()
    }
}

And the authorization flow

class AuthorizationFlow
{
    fun start()
    {
        // do some stuff
    }
}

The obvious problem is that the authFlow property within the MainFlow class is never initialized when the init gets executed. How can I "wait" for the authFlow to become initialized and only then call the authFlow.start() method? Thanks!

Upvotes: 1

Views: 2383

Answers (2)

gumil
gumil

Reputation: 126

You can do a member injection instead of making it a lateinit

class MainFlow {
    var authFlow : AuthorizationFlow? = null
        set(value) {
            field = value
            value?.start()
        }
}

The downside is now you are dealing with a nullable type.

Upvotes: 2

Francesc
Francesc

Reputation: 29260

You can use Delegates.observable:

var authFlow: AuthorizationFlow? by Delegates.observable<AuthorizationFlow?>(null) { _, old, new -> {
    if (old == null && new != null) {
        new.start()
    }
}

and remove your init block.

Upvotes: 2

Related Questions