-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
DebounceController.swift
44 lines (38 loc) · 1.08 KB
/
DebounceController.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
import Combine
import Foundation
protocol DebounceSnapshot: Equatable { }
extension String: DebounceSnapshot { }
final class DebounceController<Snapshot: DebounceSnapshot> {
enum Kind {
case keyRepeat
case keyDown
}
private var subscription: AnyCancellable?
private let kind: Kind
private let subject = PassthroughSubject<Snapshot, Never>()
private let onUpdate: (Snapshot) -> Void
@Published var snapshot: Snapshot
init(_ initialValue: Snapshot, kind: Kind = .keyRepeat, milliseconds: Int, onUpdate: @escaping (Snapshot) -> Void) {
self._snapshot = .init(initialValue: initialValue)
self.onUpdate = onUpdate
self.kind = kind
self.subscription = subject
.debounce(for: .milliseconds(milliseconds), scheduler: DispatchQueue.main)
.sink {
onUpdate($0)
}
}
func process(_ snapshot: Snapshot) {
switch kind {
case .keyDown:
subject.send(snapshot)
return
case .keyRepeat:
if LocalEventMonitor.shared.repeatingKeyDown {
subject.send(snapshot)
return
}
}
onUpdate(snapshot)
}
}