Hi there is this the correct implementation of cor...
# coroutines
h
Hi there is this the correct implementation of coroutineScope? Will this call the
someSuspendHttpRequestWithKtor
in parallel from the
map
call?
Copy code
suspend fun someCRUDMethod(models: List<MyModel>) {
    val myModels = coroutineScope {
        async {
            models.map { myAPI.someSuspendHttpRequestWithKtor(it.id) }
        }
    }
    val myListOfModels = myModels.await()
    ....
}
s
Why not just this?:
Copy code
suspend fun someCRUDMethod(models: List<MyModel>) {
    val myListOfModels = models.map { myAPI.someSuspendHttpRequestWithKtor(it.id) }
    ....
}
You want to call all
someSuspendHttpRequestWithKtor
in parallel, one async for each item in
models
?
If so, try:
Copy code
// someSuspendHttpRequestWithKtor executed in parallel
suspend fun someCRUDMethod(models: List<MyModel>) {
    val myDeferredModels = coroutineScope {
        models.map { async { myAPI.someSuspendHttpRequestWithKtor(it.id) } }
    }
    val myListOfModels = myDeferredModels.awaitAll()
    ....
}
h
No I want to wait for all of them to complete
s
In sequence, not parallel?
h
Parallel, so the second one is the optimal solution?
s
Yup, your solution executes them in sequence, once for each item. My second example launches all of them in parallel and then awaits them all.
h
Alright thanks
s
Note, though, that
awaitAll()
, in this example, does not really wait at all… it already has all the results, because
coroutineScope [ ... ]
only resumes/returns when all its children (calls to
async
) have finished. Still, the effect is the same in your example.
h
I just want the requests to be run in parallel instead of sequentially and then wait for all of them to finish before doing other things
So essentially
awaitAll()
just unboxes them from their Deferred wrapper?
s
And awaits each of them in parallel. But since all children already have finished ( because
coroutineScope
has resumed and that can only happen if all its (async) children have finished), it doesn’t really wait in this case
But in other cases, if the async children have not yet finished, the
awaitAll()
will await until all of them have finished.
h
I see. Thanks for the explanation 🙂