类和结构体对闭包封装一层
struct DelayClouserCancellable {
typealias isCancelTask = (_ isCancelled: Bool) -> ()
private var myTask: isCancelTask?
mutating public func delayTask(delayTime: TimeInterval, isMainThread: Bool, task: @escaping () -> ()) {
var trueTask: (() -> ())? = task
var proxyTask: isCancelTask?
let internalTask: isCancelTask = { isCancelled in
print("isCanceled--\(isCancelled)")
if let tempTask = trueTask, !isCancelled {
if isMainThread {
DispatchQueue.main.async(execute: tempTask)
} else {
DispatchQueue.global().async(execute: tempTask)
}
} else {
print("延迟任务被取消了")
}
proxyTask = nil
trueTask = nil
}
proxyTask = internalTask
myTask = internalTask
func doTask(_ block: @escaping () -> ()) {
DispatchQueue.global().asyncAfter(deadline: .now() + delayTime, execute: block)
}
doTask {
if let closure = proxyTask {
closure(false)
}
}
}
public mutating func cancel() {
myTask?(true)
free()
}
private mutating func free() {
if myTask != nil {
print("myTask--释放")
myTask = nil
}
}
}
class ControllableClourse {
typealias noParamsClourse = () -> ()
private static var isCancel = false
private var isCancel = false
// MARK: 类方法
public static func start(delayTime: TimeInterval, clourse: @escaping noParamsClourse) {
let time: DispatchTime = .now() + delayTime
DispatchQueue.main.asyncAfter(deadline: time) {
if !isCancel {
clourse()
}
isCancel = false
}
}
public static func cancel() {
isCancel = true
}
// MARK: 实例方法
public func start(delayTime: TimeInterval, clourse: @escaping noParamsClourse) {
let time: DispatchTime = .now() + delayTime
DispatchQueue.main.asyncAfter(deadline: time) {
if !self.isCancel {
clourse()
}
self.isCancel = false
}
}
public func cancel() {
isCancel = true
}
}
2. 但是,多次调用,再取消的时候,只能取消一个任务
class ControllableClourse {
typealias noParamsClourse = () -> ()
private var isCancel = false
private var myQueue: [DispatchWorkItem] = [DispatchWorkItem]()
// MARK: 实例方法
public func start(delayTime: TimeInterval, clourse: @escaping noParamsClourse) {
let time: DispatchTime = .now() + delayTime
let item = DispatchWorkItem {
if !self.isCancel {
clourse()
}
self.isCancel = false
}
myQueue.append(item)
while !myQueue.isEmpty {
let first = myQueue.removeFirst()
print("first--\(myQueue.count)")
DispatchQueue.main.asyncAfter(deadline: time) {
if self.myQueue.count > 0 {
first.perform()
}
}
}
}
public func cancel() {
isCancel = true
myQueue.removeAll()
print(myQueue.count)
}
}
3. 点一次取消一个任务?FIFO的形式?栈的形式?