forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelayedActionScheduler.swift
More file actions
51 lines (45 loc) · 1.2 KB
/
Copy pathDelayedActionScheduler.swift
File metadata and controls
51 lines (45 loc) · 1.2 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
import Foundation
@MainActor
protocol DelayedActionCancellation: AnyObject {
func cancel()
}
@MainActor
protocol DelayedActionScheduling {
@discardableResult
func schedule(
after interval: TimeInterval,
action: @escaping @MainActor () -> Void
) -> DelayedActionCancellation
}
@MainActor
private final class TaskDelayedActionCancellation: DelayedActionCancellation {
private var task: Task<Void, Never>?
init(task: Task<Void, Never>) {
self.task = task
}
func cancel() {
task?.cancel()
task = nil
}
}
/// Production scheduler for cancellable UI deadlines. Consumers inject a
/// manual implementation in tests, so watchdog and debounce behavior never
/// depends on wall-clock sleeps.
@MainActor
final class TaskDelayedActionScheduler: DelayedActionScheduling {
func schedule(
after interval: TimeInterval,
action: @escaping @MainActor () -> Void
) -> DelayedActionCancellation {
let task = Task { @MainActor in
do {
try await Task.sleep(nanoseconds: UInt64(max(0, interval) * 1_000_000_000))
} catch {
return
}
guard !Task.isCancelled else { return }
action()
}
return TaskDelayedActionCancellation(task: task)
}
}