Skip to content

Instantly share code, notes, and snippets.

@tahakorkem
Last active July 19, 2023 13:08
Show Gist options
  • Save tahakorkem/92dc64f6db8957707e365204f77eaaeb to your computer and use it in GitHub Desktop.
Save tahakorkem/92dc64f6db8957707e365204f77eaaeb to your computer and use it in GitHub Desktop.
Extension functions of parallel iteration over collections in Kotlin (map and forEach equivalents)
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
suspend fun <T> Collection<T>.forEachAsync(action: suspend (T) -> Unit) =
coroutineScope {
map { item ->
async { action(item) }
}.awaitAll()
}
suspend fun <T, R> Collection<T>.mapAsync(transform: suspend (T) -> R): List<R> =
coroutineScope {
map { item ->
async { transform(item) }
}.awaitAll()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment