mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-25 04:27:48 +00:00
#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:
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
|
||||
|
||||
Reference in new issue
Block a user