Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Batch subscribing and outputting in Combine.
import CombineExt
extension Collection where Element: Publisher {
func batchedSubscribe(by limit: Int) -> AnyPublisher<[Element.Output], Element.Failure> {
let indexBreaks = sequence(
first: startIndex,
next: {
$0 == endIndex ?
nil :
index($0, offsetBy: limit, limitedBy: endIndex)
?? endIndex
}
)
return Swift.zip(indexBreaks, indexBreaks.dropFirst())
.map(..<)
.publisher
.setFailureType(to: Element.Failure.self)
.flatMap(maxPublishers: .max(1)) { self[$0].zip() }
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment