Last active
December 13, 2022 16:05
-
-
Save LouisCAD/93a6e14a91b950a0a91796ab957836b5 to your computer and use it in GitHub Desktop.
Collect a Flow in parallel
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.* | |
import kotlinx.coroutines.channels.* | |
import kotlinx.coroutines.flow.* | |
suspend fun <T> Flow<T>.collectInParallel( | |
concurrency: Int, | |
collector: suspend (T) -> Unit | |
) = coroutineScope { | |
val channel: Channel<T> = Channel() | |
repeat(concurrency) { launch { for (e in channel) collector(e) } } | |
collect { channel.send(it) } | |
channel.close() | |
} | |
suspend fun <T> Flow<T>.collectInParallel( | |
collectors: List<suspend (T) -> Unit> | |
) = coroutineScope { | |
val channel: Channel<T> = Channel() | |
collectors.forEach { collector -> launch { for (e in channel) collector(e) } } | |
collect { channel.send(it) } | |
channel.close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment