Skip to content

Instantly share code, notes, and snippets.

@tailec
Forked from daltonclaybrook/ZipMany.swift
Created June 26, 2019 07:44
Show Gist options
  • Save tailec/bf37d064df79e5121def6fafbf1148b1 to your computer and use it in GitHub Desktop.
Save tailec/bf37d064df79e5121def6fafbf1148b1 to your computer and use it in GitHub Desktop.
import Combine
struct ZipMany<Element, Failure>: Publisher where Failure: Error {
typealias Output = [Element]
private let underlying: AnyPublisher<Output, Failure>
init<T: Publisher>(publishers: [T]) where T.Output == Element, T.Failure == Failure {
let zipped: AnyPublisher<[T.Output], T.Failure>? = publishers.reduce(nil) { result, publisher in
if let result = result {
return publisher.zip(result).map { element, array in
array + [element]
}.eraseToAnyPublisher()
} else {
return publisher.map { [$0] }.eraseToAnyPublisher()
}
}
underlying = zipped ?? Publishers.Empty(completeImmediately: false)
.eraseToAnyPublisher()
}
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
underlying.receive(subscriber: subscriber)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment