https://kotlinlang.org logo
Title
h

hooliooo

09/12/2019, 8:38 PM
Hi there is this the correct implementation of coroutineScope? Will this call the
someSuspendHttpRequestWithKtor
in parallel from the
map
call?
suspend fun someCRUDMethod(models: List<MyModel>) {
    val myModels = coroutineScope {
        async {
            models.map { myAPI.someSuspendHttpRequestWithKtor(it.id) }
        }
    }
    val myListOfModels = myModels.await()
    ....
}
s

streetsofboston

09/12/2019, 8:41 PM
Why not just this?:
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:
// 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

hooliooo

09/12/2019, 8:44 PM
No I want to wait for all of them to complete
s

streetsofboston

09/12/2019, 8:44 PM
In sequence, not parallel?
h

hooliooo

09/12/2019, 8:45 PM
Parallel, so the second one is the optimal solution?
s

streetsofboston

09/12/2019, 8:46 PM
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

hooliooo

09/12/2019, 8:46 PM
Alright thanks
s

streetsofboston

09/12/2019, 8:48 PM
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

hooliooo

09/12/2019, 8:53 PM
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

streetsofboston

09/12/2019, 8:55 PM
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

hooliooo

09/12/2019, 8:56 PM
I see. Thanks for the explanation 🙂