I have a question about documentation that I think...
# coroutines
s
I have a question about documentation that I think is a little misleading and wondering if someone can confirm my understanding. Specifically looking at https://kotlinlang.org/docs/reference/coroutines/basics.html#extract-function-refactoring which discusses refactoring a
suspend
function out of a block and raises this:
But what if the extracted function contains a coroutine builder which is invoked on the current scope? In this case, the 
suspend
 modifier on the extracted function is not enough.
It offers a few options:
Making 
doWorld
 an extension method on 
CoroutineScope
 is one of the solutions, but it may not always be applicable as it does not make the API clearer.
I agree that it doesn't make the API clearer and usually extensions on
CoroutineScope
are reserved for things that return immediately like the coroutine builders. Roman offered a great convention around this in a talk or blog post I believe.
The idiomatic solution is to have either an explicit 
CoroutineScope
 as a field in a class containing the target function or an implicit one when the outer class implements 
CoroutineScope
.
This makes me 🤔 . Wouldn't a more idiomatic solution be to use
coroutineScope
or
supervisorScope
from the
suspend
function that would 1) respect structured concurrency since the scope that is created would be a child of the scope that the
suspend
function was called from and 2) give you a
CoroutineScope
that would allow you to call your coroutine builder like
launch
, etc.?
o
I think wrapping the block in
coroutineScope
would be better, not sure why that isn't suggested, esp. as it is referenced above as well
s
Yeah, also correctly described in a codelab: https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/06_StructuredConcurrency
It is possible to create a new scope without starting a new coroutine. The
coroutineScope
function does this. When we need to start new coroutines in a structured way inside a suspend function without access to the outer scope, for example inside loadContributorsConcurrent, we can create a new coroutine scope which automatically becomes a child of the outer scope that this suspend function is called from.
https://github.com/Kotlin/kotlinx.coroutines/issues/2162 Opened an issue to update the documentation