Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active January 23, 2021 19:30
Show Gist options
  • Save jasdev/48a2ff15df057a05a8afd17507f36e37 to your computer and use it in GitHub Desktop.
Save jasdev/48a2ff15df057a05a8afd17507f36e37 to your computer and use it in GitHub Desktop.
Showing `Sequence.bufferedSubscribe(size)`’s non-guaranteeing of order.
import CombineExt
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 { print("Unsubscribed to \(index)") }
}
}
let cancellable = delayedIntPublishers
.publisher
.flatMap { $0 }
.collect(5)
.sink(receiveValue: { batch in print(batch) })
// Sample output:
// ```
// Subscribed to 0
// Subscribed to 1
// Subscribed to 2
// Subscribed to 3
// Subscribed to 4
// Unsubscribed to 0
// Subscribed to 5
// Unsubscribed to 4
// Subscribed to 6
// Unsubscribed to 1
// Subscribed to 7
// Unsubscribed to 3
// Subscribed to 8
// [0, 4, 1, 3, 2]
// Unsubscribed to 2
// Subscribed to 9
// Unsubscribed to 8
// Subscribed to 10
// Unsubscribed to 5
// Subscribed to 11
// Unsubscribed to 6
// Subscribed to 12
// Unsubscribed to 7
// [8, 5, 6, 7, 11]
// Unsubscribed to 11
// Unsubscribed to 10
// Unsubscribed to 9
// Unsubscribed to 12
// [10, 9, 12]
// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment