|
| 1 | +import Foundation |
| 2 | + |
| 3 | +private actor TimedDebounceFunction<Element> { |
| 4 | + let duration: TimeInterval |
| 5 | + let block: (Element) async -> Void |
| 6 | + |
| 7 | + var task: Task<Void, Error>? |
| 8 | + var lastValue: Element? |
| 9 | + var lastFireTime: Date = .init(timeIntervalSince1970: 0) |
| 10 | + |
| 11 | + init(duration: TimeInterval, block: @escaping (Element) async -> Void) { |
| 12 | + self.duration = duration |
| 13 | + self.block = block |
| 14 | + } |
| 15 | + |
| 16 | + func callAsFunction(_ value: Element) async { |
| 17 | + task?.cancel() |
| 18 | + if lastFireTime.timeIntervalSinceNow < -duration { |
| 19 | + await fire(value) |
| 20 | + task = nil |
| 21 | + } else { |
| 22 | + lastValue = value |
| 23 | + task = Task.detached { [weak self, duration] in |
| 24 | + try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000)) |
| 25 | + await self?.fire(value) |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + func finish() async { |
| 31 | + task?.cancel() |
| 32 | + if let lastValue { |
| 33 | + await fire(lastValue) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private func fire(_ value: Element) async { |
| 38 | + lastFireTime = Date() |
| 39 | + lastValue = nil |
| 40 | + await block(value) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +public extension AsyncSequence { |
| 45 | + /// Debounce, but only if the value is received within a certain time frame. |
| 46 | + func timedDebounce( |
| 47 | + for duration: TimeInterval |
| 48 | + ) -> AsyncThrowingStream<Element, Error> { |
| 49 | + return AsyncThrowingStream { continuation in |
| 50 | + Task { |
| 51 | + let function = TimedDebounceFunction(duration: duration) { value in |
| 52 | + continuation.yield(value) |
| 53 | + } |
| 54 | + do { |
| 55 | + for try await value in self { |
| 56 | + await function(value) |
| 57 | + } |
| 58 | + await function.finish() |
| 59 | + continuation.finish() |
| 60 | + } catch { |
| 61 | + continuation.finish(throwing: error) |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments