Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created March 30, 2020 15:31
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 PaulWoitaschek/34225bfdea65e042431c6e57e72768f7 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/34225bfdea65e042431c6e57e72768f7 to your computer and use it in GitHub Desktop.
@PublishedApi
internal object UnInitialized
@PublishedApi
internal inline fun <T, R> combine(vararg sources: Flow<T>, crossinline transform: suspend (List<T>) -> R): Flow<R> {
return channelFlow {
val values = Array<Any?>(sources.size) { UnInitialized }
coroutineScope {
sources.mapIndexed { index, flow ->
launch {
flow.collect { value ->
values[index] = value
if (values.all { it !== UnInitialized }) {
send(transform(values.toList() as List<T>))
}
}
}
}.joinAll()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment