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

Dominaezzz

10/10/2019, 10:19 AM
I've come with yet another
coroutineScope
vs
withContext
question. Does
coroutineScope
change the
coroutineContext
like
withContext
does? (I'm referring to the intrinsic
coroutineContext
and not
CoroutineScope.coroutineContext
). The docs aren't explicit enough to inspire confidence.
g

gildor

10/10/2019, 10:22 AM
Yes, because
coroutineContext
function creates a new coroutine with own Job (same as withContext actually)
d

Dominaezzz

10/10/2019, 10:24 AM
So
flow { coroutineScope { emit(...) } }
will not work then?
g

gildor

10/10/2019, 10:29 AM
why?
but in general it’s incorrect (tho will work for this simple case)
you should use channelFlow instead for this case
e

elizarov

10/10/2019, 11:29 AM
flow { coroutineScope { emit(....) } }
is allowed. Even though
coroutinesScope { ... }
creates a new job and a new context with it, it is considered an continuation of its parent context that runs sequentially with it. This is specifically allowed to make it possible to write:
Copy code
flow { 
    coroutineScope {
          // can launch concurrent stuff here
         launch { ... }
         // but can only emit sequentially from here
         emit(...) 
    }
}
3 Views