Created
April 2, 2021 08:29
-
-
Save davydes/b94b73925c60b0970774eb05e2fb7466 to your computer and use it in GitHub Desktop.
Kotlin Cooking Book
This file contains 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
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