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/5382af8e5e1ac56ff051cb9e33097ddb to your computer and use it in GitHub Desktop.
Save jasdev/5382af8e5e1ac56ff051cb9e33097ddb to your computer and use it in GitHub Desktop.
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