Mendess
11/15/2021, 12:10 PMfun foo() {
lateinit var x: Int
if (::x.isInitialized()) {}
}
This doesn't seem to workJoffrey
11/15/2021, 12:11 PMlateinit var
probably shouldn't be used in this case, probably nullability would work better. What is your exact use case here?Mendess
11/15/2021, 12:13 PM@Test
fun foo() {
lateinit var x: Int
someAsyncComputation { x = it }
GlobalScope.launch {
while (!::x.isInitialized()) { deplay(1000) }
// do somthing with x
}
}
Mendess
11/15/2021, 12:14 PMJoffrey
11/15/2021, 12:15 PMlateinit
is designed for avoiding null checks when you know better than the compiler that your variable will be initialized in due time. Here you really don't know (you have to manually check), so why not just use nulls?Mendess
11/15/2021, 12:17 PM!!
Mendess
11/15/2021, 12:17 PMJoffrey
11/15/2021, 12:18 PMGlobalScope
might mess up error handling of the test framework, because you're not waiting for this coroutine to finishJoffrey
11/15/2021, 12:28 PMbecause it won't do smart casting to non null I think and I'll have to useYou can also store the asserted result in another local non-null!!
val
inside the launch
, but honestly I believe you should just change the approach here.
For instance, an alternative is to use a `CompletableDeferred`:
val x = CompletableDeferred<Int>()
someAsyncComputation { x.complete(42) }
GlobalScope.launch {
val completedX = x.await()
// do somthing with completedX
}
This still doesn't solve the GlobalScope
problem, but at least you don't have this weird polling anymore.hfhbd
11/15/2021, 12:36 PMsuspendContinutation
Joffrey
11/15/2021, 12:37 PMrunBlockingTest
from kotlinx-coroutines-testJoffrey
11/15/2021, 12:38 PMsomeAsyncComputation
could be made a suspend
function instead of callback-basedMendess
11/15/2021, 12:41 PMMendess
11/15/2021, 12:41 PMsmit01
11/15/2021, 5:58 PM