forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThrottleFunction.swift
More file actions
42 lines (35 loc) · 1.07 KB
/
ThrottleFunction.swift
File metadata and controls
42 lines (35 loc) · 1.07 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
import Foundation
public actor ThrottleFunction<T> {
let duration: TimeInterval
let block: (T) async -> Void
var task: Task<Void, Error>?
var lastFinishTime: Date = .init(timeIntervalSince1970: 0)
var now: () -> Date = { Date() }
public init(duration: TimeInterval, block: @escaping (T) async -> Void) {
self.duration = duration
self.block = block
}
public func callAsFunction(_ t: T) async {
if task == nil {
scheduleTask(t, wait: now().timeIntervalSince(lastFinishTime) < duration)
}
}
func scheduleTask(_ t: T, wait: Bool) {
task = Task.detached { [weak self] in
guard let self else { return }
do {
if wait {
try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
}
await block(t)
await finishTask()
} catch {
await finishTask()
}
}
}
func finishTask() {
task = nil
lastFinishTime = now()
}
}