#113 Define the first element of throttled sequences by not exceeding the rate (and fix a expectation misalignment of events) (#133)

* #113 Define the first element of throttled sequences by not exceeding the rate (and fix a expectation misalignment of events)

* Update guide for throttle referencing the first element and duration measurement
This commit is contained in:
Philippe Hausler authored and GitHub committed 2022-04-01 11:40:44 -07:00
1 parent 6971c8fc67
commit 18749897a8
4 files changed
+15 -10

No files matched your search

@@ -64,6 +64,7 @@ extension AsyncThrottleSequence: AsyncSequence {
/// The iterator for an `AsyncThrottleSequence` instance.
public struct Iterator: AsyncIteratorProtocol {
var base: Base.AsyncIterator
var last: C.Instant?
let interval: C.Instant.Duration
let clock: C
let reducing: @Sendable (Reduced?, Base.Element) async -> Reduced
@@ -77,13 +78,15 @@ extension AsyncThrottleSequence: AsyncSequence {
public mutating func next() async rethrows -> Reduced? {
var reduced: Reduced?
let start = clock.now
let start = last ?? clock.now
repeat {
guard let element = try await base.next() else {
return nil
}
let reduction = await reducing(reduced, element)
if start.duration(to: clock.now) >= interval {
let now = clock.now
if start.duration(to: now) >= interval || last == nil {
last = now
return reduction
} else {
reduced = reduction