Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active Jan 23, 2021
Embed
What would you like to do?
A `Publisher.collect(_:)` example.
import CombineExt
let delayedIntPublishers = (0...12).map { index in
AnyPublisher<Int, Never>.create { subscriber in
print("Subscribed to \(index)")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
subscriber.send(index)
subscriber.send(completion: .finished)
}
return AnyCancellable {}
}
}
let cancellable = delayedIntPublishers
.publisher
.flatMap { $0 }
.collect(5)
.sink(receiveValue: { batch in print(batch) })
// Outputs:
// ```
// Subscribed to 0
// Subscribed to 1
// Subscribed to 2
// Subscribed to 3
// Subscribed to 4
// Subscribed to 5
// Subscribed to 6
// Subscribed to 7
// Subscribed to 8
// Subscribed to 9
// Subscribed to 10
// Subscribed to 11
// Subscribed to 12
// ```
// and then two seconds later,
// ```
// [0, 1, 2, 3, 4]
// [5, 6, 7, 8, 9]
// [10, 11, 12]
// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment