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

238 views Asked by At

I've been exploring AsyncTimerSequence from AsyncAlgorithms and found it to be a simple solution to continuously emit elements from my await function to a listener.

My problem is that the sequence only emits a value after the given interval. I know by looking through the source code that this is by design. I'd however like to emit a value immediately once some function starts listening to the sequence, and then after the specified interval.

I figured I'd have to create my own AsyncSequence (by modifying the AsyncTimerSequence) but I'd just like to know if there's a workaround that doesn't involve writing a new sequence creator.

3

There are 3 answers

0
Rob On BEST ANSWER

One can chain an asynchronous sequence consisting solely of now (via async) with the timer sequence:

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

for await tick in sequence {
    …
}
0
Magnus On

I solved it by making my own AsyncSequence, but there might be a better way to do it.

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 { }
0
Cy-4AH On

Something like?

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