https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Peter

12/01/2023, 1:38 PM
is there maybe a way, to
suspend
, until
lateinit var
is initialized?
c

CLOVIS

12/01/2023, 1:46 PM
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

Peter

12/01/2023, 1:52 PM
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

Klitos Kyriacou

12/01/2023, 3:22 PM
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.
5 Views