Skip to content

Instantly share code, notes, and snippets.

@RubyLichtenstein
Last active December 27, 2018 11:15
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/c0d4cf47bbd9b71265a7979162f9dc2b to your computer and use it in GitHub Desktop.
Save RubyLichtenstein/c0d4cf47bbd9b71265a7979162f9dc2b to your computer and use it in GitHub Desktop.
//run array of (suspend () -> Unit) in parallel
suspend fun parallel(vararg blocks: suspend () -> Unit) = runBlocking {
for (block in blocks) {
withContext(Dispatchers.Default) { block() }
}
}
//run 2 functinos in pararllel then marge the result into pair
suspend fun <T1, T2> parallel2(block1: suspend () -> T1, block2: suspend () -> T2): Pair<T1, T2> =
runBlocking {
Pair(
withContext(Dispatchers.Default) { block1() },
withContext(Dispatchers.Default) { block2() }
)
}
//wrapper around Iterable<T>.flatMap to parrallel flatMap
suspend inline fun <T, R> Iterable<T>.flatMapParallel(
crossinline transform: suspend (T) -> Iterable<R>
): List<R> = runBlocking {
flatMap { withContext(Dispatchers.Default) { transform(it) } }
}
//wrapper around Iterable<T>.map to parrallel map
suspend inline fun <T, R> Iterable<T>.mapParallel(
crossinline transform: suspend (T) -> R
): List<R> = runBlocking {
map { withContext(Dispatchers.Default) { transform(it) } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment