Why does calling a launch within a launch throw an...
# kotlin-native
s
Why does calling a launch within a launch throw an
IllegalStateException
? I don’t want to have to wrap every launch call in runblocking whenever I want to do some background work, but is there another way around that?
Copy code
// Fails
runBlocking {
    GlobalScope.launch {
        println(1)
        GlobalScope.launch { // IllegalStateException: no event loop, use runBlocking
            println(2)
        }
    }
}

// Succeeds
runBlocking {
    GlobalScope.launch {
        println(1)
        runBlocking {
            GlobalScope.launch {
                println(2)
            }
        }
    }
}
k
event loops are thread-local
definitely annoying
s
But what if I want to launch some async task without blocking execution? The
runBlocking
call blocks the calling thread until its coroutines, i.e., the nested launches, are complete.
b
you can do a nested launch without GlobalScope
s
care to elaborate?
b
oh actually nvm. i'm not actually sure how:
Copy code
runBlocking {
    GlobalScope.launch {
    }
}
works since you're explicitly calling out to a scope that isn't the
runBlocking
. without understanding that, it's hard to elaborate my initial answer 🙂
sorry