https://kotlinlang.org logo
Title
m

marcinmoskala

10/18/2021, 11:46 AM
Functions
coroutineScope
,
withContext
,
withTimeout
and
supervisorScope
have very similar behavior and this group should have a name. In some places they are referenced as "Scoping functions", but I understand this can be confused with "Scope functions". What are your feelings about that? I am considering naming them "Coroutine scope function" or "Coroutine scoping functions".
j

Joffrey

10/18/2021, 11:51 AM
Mmh I don't believe they have similar behaviour.
coroutineScope
and
supervisorScope
create a scope to allow launching coroutines, and suspend until those child coroutines terminate. These 2 could be grouped. The 2 others don't provide a scope, so they have quite different usage patterns and I don't quite get the need for a name that would encompass them as well.
withTimeout
is just a suspend function like any other, and I don't see it as related to
withContext
m

marcinmoskala

10/18/2021, 3:38 PM
@Joffrey Show me, because as far as I tested, there is no difference between
coroutineScope
,
withContext(EmptyCoroutineContext)
and
withTimeout(Long.MAX_VALUE)
. They all create scope.
j

Joffrey

10/18/2021, 3:45 PM
Apologies, then. I was answering from the top of my head, and
withTimeout
and
withContext
actually do provide a scope. That being said, they popped in such different contexts in my experience that I actually never had to consider these 4 as a group. And in particular, I never used
withTimeout
or
withContext
to actually start coroutines - just to control the timeout of some suspending code, or change the context. Starting a coroutine with
withContext
would be equivalent to just pass that context to the actual coroutine builder.
j

julian

10/18/2021, 6:46 PM
This is very interesting. I never would have thought
withTimeout
created a new scope. But I'm glad to see confirmation that
withContext
does create a new scope, rather than "just" modify context.
@marcinmoskala Do you cover this in your book on coroutines?
m

marcinmoskala

10/18/2021, 7:15 PM
Yes, this is the current state of the chapter about both of them: https://kt.academy/article/cc-scoping-functions
j

julian

10/18/2021, 7:49 PM
Great! Just bought it!
I'm about half-way through Kotlin Coroutines by @marcinmoskala. Really, really good. If you want a deep, thorough, and well-organized understanding of coroutines, there's no better single resource available. I know this because I've been looking for something like this for a couple of years. Highly recommend.
😒imple_smile: 1