Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Batched subscribe and outputting example.
let delayedIntPublishers = (0...12).map { index in
AnyPublisher<Int, Never>.create { subscriber in
print("Subscribed to \(index)")
DispatchQueue.main.asyncAfter(deadline: .now() + Double.random(in: 1...3)) {
subscriber.send(index)
subscriber.send(completion: .finished)
}
return AnyCancellable {}
}
}
let cancellable = delayedIntPublishers
.batchedSubscribe(by: 5)
.sink(receiveValue: { batch in print(batch) })
// Outputs:
// ```
// Subscribed to 0
// Subscribed to 1
// Subscribed to 2
// Subscribed to 3
// Subscribed to 4
// [0, 1, 2, 3, 4]
// Subscribed to 5
// Subscribed to 6
// Subscribed to 7
// Subscribed to 8
// Subscribed to 9
// [5, 6, 7, 8, 9]
// Subscribed to 10
// Subscribed to 11
// Subscribed to 12
// [10, 11, 12]
// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment