Skip to content

Instantly share code, notes, and snippets.

@hybridcattt
Last active November 18, 2021 16:28
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 hybridcattt/3046c329779f82232a5f9ab159cf1f22 to your computer and use it in GitHub Desktop.
Save hybridcattt/3046c329779f82232a5f9ab159cf1f22 to your computer and use it in GitHub Desktop.
A version of Publishers.CombineLatest4 that takes an unlimited number of publishers in an array
import Combine
extension Publishers {
static func CombineLatestMany<Output>(_ pubs: [AnyPublisher<Output, Never>]) -> AnyPublisher<[Output], Never> {
guard let firstPublisher = pubs.first else {
return Empty<[Output], Never>(completeImmediately: false).eraseToAnyPublisher()
}
let allButFirst = Array(pubs.dropFirst())
let firstInArray = firstPublisher.map{ [$0] }.eraseToAnyPublisher()
let combined = allButFirst.reduce(firstInArray) { partialResult, next in
partialResult
.combineLatest(next)
.map({ resultSoFar, new in
return resultSoFar + [new]
})
.eraseToAnyPublisher()
}
return combined
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment