Skip to content

Instantly share code, notes, and snippets.

@davydes
Created April 2, 2021 08:29
Show Gist options
  • Save davydes/b94b73925c60b0970774eb05e2fb7466 to your computer and use it in GitHub Desktop.
Save davydes/b94b73925c60b0970774eb05e2fb7466 to your computer and use it in GitHub Desktop.
Kotlin Cooking Book
import kotlinx.coroutines.flow.*
import kotlin.coroutines.CoroutineContext
/*
Map each elements with a concurrency level
Output elements can be shuffled
*/
suspend fun <T, R> Iterable<T>.mapConcurrently(
level: Int,
context: CoroutineContext? = null,
block: suspend (T) -> R
): Iterable<R> {
return asFlow().flatMapMerge(level) {
flow { emit(block(it)) }.let {
if (context != null) it.flowOn(context)
else it
}
}.toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment