Last active
January 23, 2021 23:26
-
-
Save jasdev/fce499fd8cb81b9640e9542d7e463bb9 to your computer and use it in GitHub Desktop.
Batch subscribing and outputting in Combine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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