Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active January 23, 2021 23:26
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 jasdev/fce499fd8cb81b9640e9542d7e463bb9 to your computer and use it in GitHub Desktop.
Save jasdev/fce499fd8cb81b9640e9542d7e463bb9 to your computer and use it in GitHub Desktop.
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