Last active
July 19, 2023 13:08
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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