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

ansman

02/27/2019, 1:59 PM
How come
coroutineScope
doesn’t accept a
CoroutineContext
to merge with the parent context?
l

louiscad

02/27/2019, 2:19 PM
@ansman You mean
CoroutineScope
? You need to use
withContext
, and the
CoroutineScope
receiver of the passed lamba will have the merged
coroutineContext
.
a

ansman

02/27/2019, 2:20 PM
No, I mean
coroutineScope
. Wanting to do structured concurrency on a specific dispatcher requires this:
Copy code
coroutineScope {
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        ...
    }
}
It would be nice if it was just
coroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
l

louiscad

02/27/2019, 2:21 PM
You don't need
coroutineScope
in that case. Using
withContext
is exactly what you need.
It creates a scope and naturally complies with structured concurrency, taking into account the context you passed to it and folding it with the one it has been called in.
a

ansman

02/27/2019, 2:22 PM
Of, of course. I forgot
withContext
creates a scope
l

louiscad

02/27/2019, 2:23 PM
Actually, allowing
coroutineScope
to be an alias to
withContext
could make sense, although it would be the very same thing. Which naming would you prefer, and why?
d

Dico

02/27/2019, 2:31 PM
coroutineScope
and
withContext
have different semantics in terms of structured concurrency
For them to be an alias would not be right
g

gildor

02/27/2019, 3:30 PM
I agree with Dico, but I also don't like name coroutineContext, although it's semantically correct, it cause a lot of misunderstanding and doesn't help understand the use case of it without reading documentation
e

elizarov

02/27/2019, 7:14 PM
I am open for suggestions on better name.
withContext { ... }
without parameters does not look right either.
d

Dico

02/27/2019, 7:19 PM
Do you mean that you think they could be aliases? As in, they do the same thing semantically.
e

elizarov

02/27/2019, 7:21 PM
Semantically they are the same. They even share code, but
withContext
does more things to figure out if you are actually changing context.
d

Dico

02/27/2019, 7:23 PM
Then I think I'm confusing this with something else completely
g

gildor

02/28/2019, 12:17 AM
How about
awaitScope
, we already have
awaitAll
, where we pass vararg of Deferred, in this case we pass lambda with receiver that becomes CoroutineScope. Not perfect semantically, but clear that this call will suspend until scope is active
👍 2
a

ansman

02/28/2019, 6:06 PM
I think I prefer
coroutineScope(context)
g

gildor

03/01/2019, 1:44 AM
what the point of
coroutineScope(context)
? To replace withCcontext? It’s counterintuitive imo, withContext is better name that run some block with passed context, it was there before StructuredConcurrency and scopes
5 Views