Last active
November 24, 2018 13:08
-
-
Save RubyLichtenstein/08841c2cffe3533fb4253369981a1264 to your computer and use it in GitHub Desktop.
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
suspend fun parallel(vararg blocks: suspend () -> Unit) { | |
for (block in blocks) { | |
GlobalScope.async { block() }.await() | |
} | |
} | |
suspend fun <T1, T2> parallel2(block1: suspend () -> T1, block2: suspend () -> T2): Pair<T1, T2> { | |
return Pair(GlobalScope.async { block1() }.await(), GlobalScope.async { block2() }.await()) | |
} | |
suspend inline fun <T, R> Iterable<T>.flatMapAsync( | |
scope: CoroutineScope = GlobalScope, | |
crossinline transform: suspend (T) -> Iterable<R> | |
): List<R> { | |
val destination = mutableListOf<R>() | |
for (element in this) { | |
val list = scope.async { transform(element) }.await() | |
destination.addAll(list) | |
} | |
return destination | |
} | |
suspend inline fun <T, R> Iterable<T>.mapAsync( | |
scope: CoroutineScope = GlobalScope, | |
crossinline transform: suspend (T) -> R | |
): List<R> { | |
val destination = mutableListOf<R>() | |
for (item in this) | |
destination.add(scope.async { transform(item) }.await()) | |
return destination | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
suspend inline fun <T, R> Iterable<T>.mapAsync(crossinline transform: suspend (T) -> R): List<R> { val destination = mutableListOf<R>() for (item in this) { destination.add(withContext(coroutineContext) { transform(item) }) } return destination }
Wouldn't that give you the same result without requiring the use of GlobalScope