-
-
Notifications
You must be signed in to change notification settings - Fork 428
Expand file tree
/
Copy pathThrottleFunction.swift
More file actions
79 lines (67 loc) · 2.09 KB
/
ThrottleFunction.swift
File metadata and controls
79 lines (67 loc) · 2.09 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
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 @Sendable (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()
}
}
public actor ThrottleRunner {
let duration: TimeInterval
var lastFinishTime: Date = .init(timeIntervalSince1970: 0)
var now: () -> Date = { Date() }
var task: Task<Void, Error>?
public init(duration: TimeInterval) {
self.duration = duration
}
public func throttle(block: @escaping @Sendable () async -> Void) {
if task == nil {
scheduleTask(wait: now().timeIntervalSince(lastFinishTime) < duration, block: block)
}
}
func scheduleTask(wait: Bool, block: @escaping @Sendable () async -> Void) {
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()
await finishTask()
} catch {
await finishTask()
}
}
}
func finishTask() {
task = nil
lastFinishTime = now()
}
}