ursus
10/12/2021, 4:36 PMprivate 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?Joffrey
10/12/2021, 4:39 PMcoroutineScope
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:
private suspend fun prefetchStories(stories: List<Story>) {
coroutineScope {
stories.forEach { story ->
launch {
prefetchStory(story)
}
}
}
}
uli
10/12/2021, 4:39 PMawaitAll
. Neither for async.
private suspend fun prefetchStories(stories: List<Story>) {
coroutineScope {
for (story in stories) {
launch {
prefetchStory(story)
}
}
}
}
`coroutineScope`will wait for all children.Joffrey
10/12/2021, 4:40 PMuli
10/12/2021, 4:40 PMJoffrey
10/12/2021, 4:42 PMprefetchStory
calls, you would indeed write something similar to what you have, although you can simplify it a bit using `map`:
private suspend fun prefetchStories(stories: List<Story>): List<PREFETCH_RETURN_TYPE> {
return coroutineScope {
stories.map { story ->
async {
prefetchStory(story)
}
}.awaitAll()
}
}
ursus
10/12/2021, 4:48 PM