I want to downlaod list of assets in parallel, is ...
# coroutines
u
I want to downlaod list of assets in parallel, is this correct?
Copy code
private suspend fun prefetchStories(stories: List<Story>) {
    coroutineScope {
        val fetches = mutableListOf<Deferred<Unit>>()
        for (story in stories) {
            fetches += async {
                prefetchStory(story)
            }
        }
        fetches.awaitAll()
    }
}
Unsure about the
coroutineScope
. Most example don't use it but I presume that means they're using GlobalScope, right?
j
coroutineScope
is the recommended way to go when you're inside a
suspend
function and want to parallelize some work, and wait for everything before returning. Since you don't need results, there is no point in using
async
, you can simply use
launch
instead. Also,
coroutineScope
will automatically wait for child coroutines to finish so you don't need to explicitly wait for them:
Copy code
private suspend fun prefetchStories(stories: List<Story>) {
    coroutineScope {
        stories.forEach { story ->
            launch {
                prefetchStory(story)
            }
        }
    }
}
u
No need for `fetches`and
awaitAll
. Neither for async.
Copy code
private suspend fun prefetchStories(stories: List<Story>) {
    coroutineScope {
        for (story in stories) {
            launch {
                prefetchStory(story)
            }
        }
    }
}
`coroutineScope`will wait for all children.
j
@uli pretty close 😄
u
🤣
you were first though. and i guess we are right. or at least “the same wrong”
j
I'm not sure this qualifies as being first, given how close in time we posted our answers - but I find it pretty funny how similar they are 😆
@ursus if you needed to gather results from
prefetchStory
calls, you would indeed write something similar to what you have, although you can simplify it a bit using `map`:
Copy code
private suspend fun prefetchStories(stories: List<Story>): List<PREFETCH_RETURN_TYPE> {
    return coroutineScope {
        stories.map { story ->
            async {
                prefetchStory(story)
            }
        }.awaitAll()
    }
}
👍 1
u
the scope reference was what I was after in a plain suspend fun, thanks!