Vikas Singh
09/16/2021, 4:42 PMJoffrey
09/16/2021, 5:57 PMcoroutineScope { ... }
blocks so you make sure they all finish before returning from your method. And in that case, the caller is responsible for starting long-lived coroutines with whatever scope it has.
Having a scope is only useful when you want to launch coroutines that outlive your function/method. What's your use case for launching long-lived coroutines in such a class? If you really have a compelling one, you can indeed pass a CoroutineScope
to enable launching coroutines, but first make sure it makes sense for the use case.
If the class has some sort of lifecycle, you can also create your own CoroutineScope
and make sure to cancel it in whatever hook you have for the end of your class's lifecycle (e.g. a close()
method).Vikas Singh
09/16/2021, 6:16 PMJoffrey
09/16/2021, 6:20 PMCoroutineScope
interface defines object that have their own lifecycle and you can use them to launch coroutines. When the scope is canceled, all child coroutines end. The opposite is not true. If a coroutine ends normally, it doesn't cancel the scope (however it does cancel the scope if it fails with an exception, unless you're using a SupervisorScope
).
The coroutineScope
function on the other hand is a suspending function, and resumes when all child coroutines inside are done.Vikas Singh
09/16/2021, 6:28 PMJoffrey
09/16/2021, 9:06 PMscope.launch {
doSomethingSuspending()
}
Here launch
starts a new coroutine in the given scope
. When doSomethingSuspending
is done, the coroutine started by launch
is also done (no need to cancel it).