Last active
December 27, 2018 11:15
-
-
Save RubyLichtenstein/c0d4cf47bbd9b71265a7979162f9dc2b 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
//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