如何使用 AsyncTimerSequence 获取初始时钟,然后开始迭代指定的时间间隔?

How can I using AsyncTimerSequence get the initial clock and then start iterating over the specified interval?

提问人:Magnus 提问时间:11/3/2023 更新时间:11/3/2023 访问量:95

问:

我一直在探索 AsyncAlgorithms,发现这是一个简单的解决方案,可以连续地将元素从我的 await 函数发射到侦听器。AsyncTimerSequence

我的问题是序列只在给定间隔后发出一个值。通过查看源代码,我知道这是设计使然。但是,我想在某个函数开始侦听序列后立即发出一个值,然后在指定的间隔之后发出一个值。

我想我必须创建自己的(通过修改 ),但我只想知道是否有不涉及编写新序列创建器的解决方法。AsyncSequenceAsyncTimerSequence

Swift 异步 swift 并发

评论


答:

0赞 Magnus 11/3/2023 #1

我通过制作自己的来解决它,但可能有更好的方法可以做到这一点。AsyncSequence

public struct AsyncInitialTimerSequence<C: Clock>: AsyncSequence {
    public typealias Element = C.Instant
    
    /// The iterator for an `AsyncInitialTimerSequence` instance.
    public struct Iterator: AsyncIteratorProtocol {
        var clock: C?
        let interval: C.Instant.Duration
        let tolerance: C.Instant.Duration?
        var last: C.Instant?
        
        init(interval: C.Instant.Duration, tolerance: C.Instant.Duration?, clock: C) {
            self.clock = clock
            self.interval = interval
            self.tolerance = tolerance
        }
        
        public mutating func next() async -> C.Instant? {
            guard let clock = self.clock else {
                return nil
            }
            
            if self.last == nil {
                let now = clock.now
                self.last = now
                return now
            }
            
            let next = (self.last ?? clock.now).advanced(by: self.interval)
            do {
                try await clock.sleep(until: next, tolerance: self.tolerance)
            } catch {
                self.clock = nil
                return nil
            }
            let now = clock.now
            self.last = next
            return now
        }
    }
    
    let clock: C
    let interval: C.Instant.Duration
    let tolerance: C.Instant.Duration?
    
    /// Create an `AsyncInitialTimerSequence` with a given repeating interval.
    public init(interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) {
        self.clock = clock
        self.interval = interval
        self.tolerance = tolerance
    }
    
    public func makeAsyncIterator() -> Iterator {
        Iterator(interval: interval, tolerance: tolerance, clock: clock)
    }
}

extension AsyncInitialTimerSequence {
    /// Create an `AsyncInitialTimerSequence` with a given repeating interval.
    public static func repeating(every interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncInitialTimerSequence<C> {
        return AsyncInitialTimerSequence(interval: interval, tolerance: tolerance, clock: clock)
    }
}

extension AsyncInitialTimerSequence where C == SuspendingClock {
    /// Create an `AsyncInitialTimerSequence` with a given repeating interval.
    public static func repeating(every interval: Duration, tolerance: Duration? = nil) -> AsyncInitialTimerSequence<SuspendingClock> {
        return AsyncInitialTimerSequence(interval: interval, tolerance: tolerance, clock: SuspendingClock())
    }
}

extension AsyncInitialTimerSequence: Sendable { }
extension AsyncInitialTimerSequence.Iterator: Sendable { }
1赞 Cy-4AH 11/3/2023 #2

像这样的东西?

func listen() async -> AsyncThrowingStream<Value> {
    var firstTime = true
    return AsyncThrowingStreamStream {
        if !firstTime {
            try await Task.sleep(someDuration)
        }
        firstTime = false
        return try await emmiter()
    }
}
3赞 Rob 11/3/2023 #3

可以将仅由 now 组成的异步序列(通过异步)与计时器序列链接起来:

let clock = ContinuousClock()
let timerSequence = AsyncTimerSequence(interval: .seconds(1), clock: clock)
let sequence = chain([clock.now].async, timerSequence)

for await tick in sequence {
    …
}