Skip to content

Instantly share code, notes, and snippets.

@RubyLichtenstein
Last active November 24, 2018 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RubyLichtenstein/08841c2cffe3533fb4253369981a1264 to your computer and use it in GitHub Desktop.
Save RubyLichtenstein/08841c2cffe3533fb4253369981a1264 to your computer and use it in GitHub Desktop.
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
}
@dorsamet
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment