Lazy async inside suspend function blocks forever?...
# coroutines
l
Lazy async inside suspend function blocks forever? I have such code:
Copy code
fun main() = runBlocking {
        sth().await()
    }

    suspend fun sth() = coroutineScope {
        async(start = CoroutineStart.LAZY) {
            println("async execution")
        }
    }
The main function blocks forever, and the “async execution” is never printed. Could anyone give a hand, thanks. 😘
g
Yes, it’s expected behavior
this is how
coroutineScope
function works: suspend until all child coroutines are finished, this is main use case of this function
it may be not so obvious with lazy, because coroutine is not started, but lazy also can be started at any moment, so if coroutineScope will return it will leak child coroutine
😘 1
l
Thanks for the quick reply! So in such case, when sth() returns, the coroutineScope is completed. Am I actually calling await on a Deferred with completed coroutine context.
g
in this particular case
sth()
never returns because coroutineScope is suspended and not completed
l
Oh I see, that is because deferred(it’s child coroutine) is not completed. thanks~
g
Yes, it’s because async is not completed and you don’t have any code that start this child coroutine and complete
l
Thanks so much. I’ll dive into the source code a bit.
g
l
I misunderstood the purpose of this function. I thought it is designed to access current coroutine context from a suspend function. actually it’s not and there is a
Copy code
public suspend inline val coroutineContext: CoroutineContext
for accessing context.
g
yes,
coroutineContext
is intrinsic that available in any suspend function