-
Notifications
You must be signed in to change notification settings - Fork 7
/
Throttler.swift
158 lines (138 loc) · 5.07 KB
/
Throttler.swift
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//
// Throttler.swift
//
//
// Created by Thibault Wittemberg on 28/09/2022.
//
import Foundation
public extension Task where Failure == Never {
/// Creates a `Regulator` that executes the output with either the most-recent or first element
/// pushed in the Throttler in the specified time interval
/// - dueTime: the interval at which to find and emit either the most recent or the first element
/// - latest: true if output should be called with the most-recent element, false otherwise
/// - output: the block to execute once the regulation is done
/// - Returns: the throttled regulator
static func throttle(
dueTime: DispatchTimeInterval,
latest: Bool = true,
output: @Sendable @escaping (Success) async -> Void
) -> some Regulator<Success> {
Throttler(dueTime: dueTime, latest: latest, output: output)
}
}
/// Executes the output with either the most-recent or first element pushed in the Throttler in the specified time interval
///
/// ```swift
/// let throttler = Throttler<Int>(dueTime: .seconds(2), latest: true, output: { print($0) })
///
/// for index in (0...99) {
/// DispatchQueue.global().asyncAfter(deadline: .now().advanced(by: .milliseconds(100 * index))) {
/// // pushes a value every 100 ms
/// throttler.push(index)
/// }
/// }
///
/// // will only print an index once every 2 seconds (the latest received index before the `tick`)
/// ```
public final class Throttler<Value>: @unchecked Sendable, ObservableObject, Regulator {
struct StateMachine {
enum State {
case idle
case throttlingWithNoValues
case throttlingWithFirst(first: Value)
case throttlingWithFirstAndLast(first: Value, last: Value)
}
var state: State = .idle
mutating func newValue(_ value: Value) -> Bool {
switch self.state {
case .idle:
self.state = .throttlingWithFirst(first: value)
return true
case .throttlingWithFirst(let first), .throttlingWithFirstAndLast(let first, _):
self.state = .throttlingWithFirstAndLast(first: first, last: value)
return false
case .throttlingWithNoValues:
self.state = .throttlingWithFirst(first: value)
return false
}
}
enum HasTickedOutput {
case finishThrottling
case continueThrottling(first: Value, last: Value)
}
mutating func hasTicked() -> HasTickedOutput {
switch state {
case .idle:
fatalError("inconsistent state, a value was being debounced")
case .throttlingWithFirst(let first):
self.state = .throttlingWithNoValues
return .continueThrottling(first: first, last: first)
case .throttlingWithFirstAndLast(let first, let last):
self.state = .throttlingWithNoValues
return .continueThrottling(first: first, last: last)
case .throttlingWithNoValues:
self.state = .idle
return .finishThrottling
}
}
}
public var output: (@Sendable (Value) async -> Void)?
public var dueTime: DispatchTimeInterval
private let latest: Bool
private let lock: os_unfair_lock_t = UnsafeMutablePointer<os_unfair_lock_s>.allocate(capacity: 1)
private var stateMachine = StateMachine()
private var task: Task<Void, Never>?
public convenience init() {
self.init(dueTime: .never, latest: true, output: nil)
}
/// A Regulator that emits either the most-recent or first element received during the specified interval
/// - Parameters:
/// - dueTime: the interval at which to find and emit either the most recent or the first element
/// - latest: true if output should be called with the most-recent element, false otherwise
/// - output: the block to execute once the regulation is done
public init(
dueTime: DispatchTimeInterval,
latest: Bool = true,
output: (@Sendable (Value) async -> Void)? = nil
) {
self.lock.initialize(to: os_unfair_lock())
self.dueTime = dueTime
self.latest = latest
self.output = output
}
public func push(_ value: Value) {
var shouldStartAThrottle = false
os_unfair_lock_lock(self.lock)
shouldStartAThrottle = self.stateMachine.newValue(value)
os_unfair_lock_unlock(self.lock)
if shouldStartAThrottle {
self.task = Task { [weak self] in
guard let self = self else { return }
await withTaskGroup(of: Void.self) { group in
loop: while true {
try? await Task.sleep(nanoseconds: self.dueTime.nanoseconds)
var hasTickedOutput: StateMachine.HasTickedOutput
os_unfair_lock_lock(self.lock)
hasTickedOutput = self.stateMachine.hasTicked()
os_unfair_lock_unlock(self.lock)
switch hasTickedOutput {
case .finishThrottling:
break loop
case .continueThrottling(let first, let last):
group.addTask {
await self.output?(self.latest ? last : first)
}
continue loop
}
}
}
}
}
}
public func cancel() {
self.task?.cancel()
}
deinit {
self.cancel()
}
}