A way to launch new coroutines inside a coroutine,...
# coroutines
f
A way to launch new coroutines inside a coroutine, without creating a new scope (i.e. using the current coroutine's scope), seems to be
CoroutineScope(coroutineContext).launch {...}
. 1) Is there a better way? 2) Is this a bad practice?
e
It is a bad practice. When you do this, what scope you expect this coroutine to run it? You don’t have any control on the scope in this code. It can be a scope of some long-running actor or a scope of some short-living function. If you truly don’t care, then just use
GlobalScope.launch
. However, much better and recommended approach is to actually think about that, figure out what scope in your application naturally controls your coroutine and explicitly use that scope.
The reasonable and good default is to assume “no left-over resources after function call” policy and to use
coroutineScope { ... }
always when you want to run some concurrent subtasks.
The exception would be functions whose sole purpose is to launch some concurrent task and return quickly. These function should either use the proper scope or if they are universal and can be used in various scopes, then they should be defined as extension functions on
CoroutineScope
.