Skip to content

Instantly share code, notes, and snippets.

@kshivang
Last active March 14, 2023 16:50
Show Gist options
  • Save kshivang/ae1315c497d59d2dea9e326dace59dfe to your computer and use it in GitHub Desktop.
Save kshivang/ae1315c497d59d2dea9e326dace59dfe to your computer and use it in GitHub Desktop.
CombineLatest extension for publisher array
// [publisher1, publisher2].combineLatest()
extension Array where Element: Publisher {
func combineLatest() -> AnyPublisher<[Element.Output], Element.Failure> {
Publishers.CombineLatestArray(self)
}
}
// Publishers.CombineLatestArray([publisher1, publisher2])
extension Publishers {
static func CombineLatestArray<P>(_ array: [P]) -> AnyPublisher<[P.Output], P.Failure> where P : Publisher {
array.dropFirst().reduce(into: AnyPublisher(array[0].map{[$0]})) { res, ob in
res = res.combineLatest(ob) { i1, i2 -> [P.Output] in
return i1 + [i2]
}.eraseToAnyPublisher()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment