forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimedDebounce.swift
More file actions
69 lines (61 loc) · 1.98 KB
/
TimedDebounce.swift
File metadata and controls
69 lines (61 loc) · 1.98 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
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
) -> AsyncThrowingStream<Element, Error> {
return AsyncThrowingStream { continuation in
Task {
let function = TimedDebounceFunction(duration: duration) { value in
continuation.yield(value)
}
do {
for try await value in self {
await function(value)
}
await function.finish()
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
}
}