I’m currently learning about Coroutines. I’am following JetBrains’ hands-on: Intro to coroutines and channels. In Structured concurrency section, they mentioned this:
It’s possible to create a new scope without starting a new coroutine, by using the
coroutineScope
function. To start new coroutines in a structured way inside asuspend
function without access to the outer scope, you can create a new coroutine scope that automatically becomes a child of the outer scope that thissuspend
function is called from.
Let’s say from inside a CoroutineScope, I’am calling a function loadUsers. These 3 implementations gave me the same result :
import kotlinx.coroutines.coroutineScope
suspend fun loadUsers(): List<User> {
coroutineScope {
//...
}
}
suspend fun loadUsers(): List<User> {
CoroutineScope(Dispatchers.Default).run {
//...
}
}
suspend fun CoroutineScope.loadUsers(): List<User> {
//...
}
Note: In the body I'am launching multiple coroutines. The full function code could be found in the Hands-on (modified in the question for simplicity).
Could someone answer these 2 questions :
- What’s the difference between the 3 implementations ?
- Are they some use cases that are requiring coroutineScope (lowel case C) and can’t be done without it ?
Thanks in advance.
I have seen this already: Difference between CoroutineScope and coroutineScope in Kotlin, but as I mentioned, the 3 styles gave me the same result, so I'm still confused about it.