Arjan van Wieringen03/26/2023, 6:59 AM
Sam03/26/2023, 7:25 AM
Arjan van Wieringen03/26/2023, 7:34 AM
Sam03/26/2023, 8:02 AM
function is for concurrent decomposition (also sometimes called parallel decomposition), and lets you break down a task into multiple concurrent subtasks. Because it encapsulates all of the coroutines that you launch inside it, and waits for them to complete or fail, the caller doesn't need to know anything about what's going on inside. It's like a coroutine "black box". From the point of view of the caller, a function that uses
to decompose its execution into concurrent subtasks should be indistinguishable from any other
function. • The
is for bridging non-coroutine code with coroutine code. It should be used rarely and with caution. Generally it should only be used at application entrypoints. The crucial difference really comes down to composability. With
, you split a coroutine into multiple coroutines, which means that each of those child coroutines can be further decomposed if you want. Whereas with
you transform a thread into one or more coroutines, which is a fundamental change of paradigm and is not composable.
emphasises the fact that it blocks the thread, which is important because it highlights the fact that it should not be called from a coroutine and is thus not composable. The blocking is the important attribute. Whereas with
, the suspending is less significant; the interesting thing is the decomposition and the encapsulated scope. That's just my take, though.
would probably not be included at all if the coroutines API could be redesigned with the benefit of hindsight.
Joffrey03/26/2023, 8:09 AM
wouldn't make much sense. When calling
we are already in a suspending context, so there is no point in a
. The point here is to create a coroutine scope locally in order to launch multiple concurrent child coroutines and wait for their result. The name puts the emphasis on that.
Sam03/26/2023, 8:11 AM
must create its own (by default) whereas
simply inherits. The dispatcher used by
is a source of much woe 😬
Joffrey03/26/2023, 8:14 AM
inherits the context from the current coroutine (because there is a current coroutine), while
creates a new context from scratch
Sam03/26/2023, 8:21 AM
Joffrey03/26/2023, 8:24 AM
being absent from coroutines if they were redesigned. Surely there would have been a way to bridge blocking and coroutine worlds
Sam03/26/2023, 8:26 AM
if coroutines are needed. But of course reality is never that easy.
suspend fun main