-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDispatchQueue.AsyncAfterC.swift
51 lines (43 loc) · 1.49 KB
/
DispatchQueue.AsyncAfterC.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
//
// dispatch_after_cancellable.swift
// BluetoothContactTransport
//
// Created by Nick Brook on 08/08/2016.
// Copyright © 2016 AfterCross. All rights reserved.
//
import Foundation
private var cancelledTokens: Set<DispatchQueue.AfterCToken> = []
private let internalQueue = DispatchQueue(label: "DispatchQueue.asyncAfterC.internal", attributes: [])
extension DispatchQueue {
typealias AfterCToken = UUID
func asyncAfterC(deadline: DispatchTime, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = DispatchWorkItemFlags(rawValue: 0), execute work: @escaping @convention(block) () -> Swift.Void) -> AfterCToken {
let t: DispatchQueue.AfterCToken = UUID()
self.asyncAfter(deadline: deadline, execute: {
var cancelled: Bool = false
_ = internalQueue.sync {
cancelled = cancelledTokens.contains(t)
if cancelled {
cancelledTokens.remove(t)
}
}
if cancelled {
return
}
work()
})
return t
}
static func asyncAfterCCancel(token: AfterCToken) {
_ = internalQueue.sync {
cancelledTokens.insert(token)
}
}
func asyncAfterCCancel(token: AfterCToken) {
DispatchQueue.asyncAfterCCancel(token: token)
}
}
extension DispatchTime {
static func fromNow(time: TimeInterval) -> DispatchTime {
return DispatchTime.now() + time
}
}