https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Landerl Young

02/21/2019, 8:53 AM
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

gildor

02/21/2019, 8:54 AM
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

Landerl Young

02/21/2019, 9:00 AM
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

gildor

02/21/2019, 9:02 AM
in this particular case
sth()
never returns because coroutineScope is suspended and not completed
l

Landerl Young

02/21/2019, 9:03 AM
Oh I see, that is because deferred(it’s child coroutine) is not completed. thanks~
g

gildor

02/21/2019, 9:03 AM
Yes, it’s because async is not completed and you don’t have any code that start this child coroutine and complete
l

Landerl Young

02/21/2019, 9:04 AM
Thanks so much. I’ll dive into the source code a bit.
g

gildor

02/21/2019, 9:06 AM
l

Landerl Young

02/21/2019, 9:14 AM
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

gildor

02/21/2019, 9:24 AM
yes,
coroutineContext
is intrinsic that available in any suspend function
3 Views