Hi! Is there any known cases when `GlobalScope.lau...
# coroutines
v
Hi! Is there any known cases when
GlobalScope.launch(Dispatchers.Unconfined)
will actually dispatch? I stumbled upon some case when
GlobalScope.launch(start = CoroutineStart.UNDISPATCHED, context = Dispatchers.Unconfined)
!=
GlobalScope.launch(Dispatchers.Unconfined)
but I can’t quite figure what’s causing it
o
if you can create a test case, I might have some ideas, but I think those two should be equivalent from what I know
v
I’m trying but no luck in reproducing it in simple environment yet unfortunately. I will get back if I manage to.
Okay, I managed to pinpoint it. This has something to do with Android
Dispatchers.Main.immediate
parent context. Simple test:
Copy code
GlobalScope.launch(Dispatchers.Main.immediate) {
            GlobalScope.launch(Dispatchers.Unconfined) {
                println("$coroutineContext: before")
            }
            println("$coroutineContext: after")
        }
It prints:
Copy code
[CoroutineId(3), "coroutine#3":StandaloneCoroutine{Active}@229841e, Main [immediate]]: after
[CoroutineId(4), "coroutine#4":StandaloneCoroutine{Active}@f2294ff, Unconfined]: before
And if I use
start = CoroutineStart.UNDISPATCHED
it works correctly.
o
I think the key here is
DispatchedContinuation<*>.executeUnconfined
-- when you are already in an event loop (which I believe Dispatchers.Main.immediate counts as well) it will not immediately execute, but re-dispatch for later to avoid stack overflows
CoroutineStart.UNDISPATCHED
is a little more strict and does not use the event loop to avoid stack overflows
v
Strange. Using
Dispatchers.Main
yield correct result:
Copy code
[CoroutineId(29), "coroutine#29":StandaloneCoroutine{Active}@c6ed5c2, Unconfined]: before
[CoroutineId(25), "coroutine#25":StandaloneCoroutine{Active}@65e4fd3, Main]: after
o
correct, because the non-immediate one does not use the undispatched event loop
v
But do
Main.immediate
and
Unconfined
share the same event loop to avoid stack overflows? Is it not a private implementation detail?
o
yes, they share the same event loop. I believe it is technically an implementation detail of how coroutines are dispatched when
CoroutineDispatcher.isDispatcherNeeded
returns false, which means that they share it because it is the same mechanism
v
I see. Thank you for your time and help