forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimedDebounce.swift
More file actions
94 lines (84 loc) · 2.84 KB
/
TimedDebounce.swift
File metadata and controls
94 lines (84 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import Foundation
private actor TimedDebounceFunction<Element> {
let duration: TimeInterval
let block: (Element) async -> Void
var task: Task<Void, Error>?
var lastValue: Element?
var lastFireTime: Date = .init(timeIntervalSince1970: 0)
init(duration: TimeInterval, block: @escaping (Element) async -> Void) {
self.duration = duration
self.block = block
}
func callAsFunction(_ value: Element) async {
task?.cancel()
if lastFireTime.timeIntervalSinceNow < -duration {
await fire(value)
task = nil
} else {
lastValue = value
task = Task.detached { [weak self, duration] in
try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
await self?.fire(value)
}
}
}
func finish() async {
task?.cancel()
if let lastValue {
await fire(lastValue)
}
}
private func fire(_ value: Element) async {
lastFireTime = Date()
lastValue = nil
await block(value)
}
}
public extension AsyncSequence {
/// Debounce, but only if the value is received within a certain time frame.
///
/// In the future when we drop macOS 12 support we should just use chunked from AsyncAlgorithms.
func timedDebounce(
for duration: TimeInterval,
reducer: @escaping @Sendable (Element, Element) -> Element
) -> AsyncThrowingStream<Element, Error> {
return AsyncThrowingStream { continuation in
Task {
let storage = TimedDebounceStorage<Element>()
var lastTimeStamp = Date()
do {
for try await value in self {
await storage.reduce(value, reducer: reducer)
let now = Date()
if now.timeIntervalSince(lastTimeStamp) >= duration {
lastTimeStamp = now
if let value = await storage.consume() {
continuation.yield(value)
}
}
}
if let value = await storage.consume() {
continuation.yield(value)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
}
}
private actor TimedDebounceStorage<Element> {
var value: Element?
func reduce(_ value: Element, reducer: (Element, Element) -> Element) async {
if let existing = self.value {
self.value = reducer(existing, value)
} else {
self.value = value
}
}
func consume() -> Element? {
defer { value = nil }
return value
}
}