is there maybe a way, to `suspend`, until `lateini...
# getting-started
p
is there maybe a way, to
suspend
, until
lateinit var
is initialized?
c
Not in an efficient way. You could actively await the value, but that's not performant.
Copy code
lateinit var foo: String

suspend fun await(): String {
    while (isActive) {
        if (this::foo.isInitialized)
            return foo
        delay(10)
    }
}
If you can, it would be better to replace the
lateinit var
by a
CompletableDeferred
, but I don't think there is an API to check if it has finished yet? Something like
Copy code
class Foo(
    scope: CoroutineScope
) {
    val foo = scope.async {
        …
    }
}
and now you can
foo.foo.await()
.
p
Thanks for suggestions. I basically have some base class, that has an injected parameter. I kind of want to avoid constructor argument, since it would affect a lot of subclasses.
Copy code
abstract class X @Inject constructor() {
    @Inject
    lateinit var y: Y
}
k
Depending on your DI framework, your lateinit var probably won't get initialized asynchronously, but instead will be initialized in a well-defined and predictable order, so you may be able to know at a given point, that the variable will or will not have been initialized.