What's the difference in semantics between `Corout...
# coroutines
l
What's the difference in semantics between
CoroutineScope.launch { }.join()
and
withContext(CoroutineScope.context) { }
?
j
launch
starts a concurrent operation, while
withContext
just switches the context but runs the piece of code in-place.
l
@Joffrey yup I forgor adding
.join()
s
The call to launch returns immediately, launching the coroutine and continues with what follows The withContext waits (suspends) until the code inside of it has finished
j
Ah, with the edit, then the launch+join is just an overly complicated way to represent it
You should never use launch+join without code in between
l
as for the second comment ofc it's just for example purposes
s
The join() call is a suspending call. It will be called in the CoroutineScope of whatever calls this join(), but the coroutine is launched in a separate/different CoroutineScope (the receiver part of the call to launch()). Cancellation here will be more complicated
🙏 1
j
> as for the second comment ofc it's just for example purposes 🤔 then what's your question?
l
@Joffrey if there's a difference in behaviour between the two
the codeblock being empty is just in this example
j
Ah, sorry I wasn't talking about the code block being empty. I was talking about the absence of code between
launch { ...}
and
join()
. If you chain
launch { ... }.join()
, then there is no point in starting a concurrent operation, because no code will effectively run concurrently with it
l
ahhh I get you
I do have a point tho, GLFW (esp. MacOS) threading shenanigans
j
But yeah it should behave pretty similarly to
withContext
in that case
🙏 1
I do have a point tho, GLFW (esp. MacOS) threading shenanigans
What is your point then? Because IMO you can always replace
launch { ... }.join()
with
withContext(...) { ... }
l
@Joffrey cancelling all coroutines after
glfwTerminate
via a
SupervisorJob
s
You can call
launch {}.join()
only with providing a separate CoroutineScope to the
launch
call....
otherScope.launch().join()
and you'd call this in yet another CoroutineScope context.
And if you use the
coroutineScope { launch { ... } }
instead, then a join() is not needed (since
coroutineScope
only resumes after all its child-coroutines have finished)