The difference between suspend fun doSomething()
and fun CoroutineScope.doSomething()
is one of the key points of structured concurrency.
A suspend fun doSomething()
guarantees that it will always complete all work before returning. By using the coroutineScope
builder it can launch “internal” coroutines that are not exposed to the caller. A caller can be sure that no new work is running at the time doSomething
returns.
A fun CoroutineScope.doSomething()
is passed a scope in which it may launch a new long-lived coroutine. A caller should expect that calling this version of doSomething
will create a new coroutine in the passed scope that lives longer than the call of doSomething
. This is mostly not needed in production, but is available when you want to build custom coroutine builders (e.g. alternatives to async
).