Swift asyns 封装思路

Aynscs.swift

public typealias Task = () -> Void

public struct Aynscs {
    
    // 异步
    public static func asyns(task: @escaping Task) {
        _asyns(task: task)
    }
    
    // 异步完成 -> 同步
    public static func asyns(task: @escaping Task, mainTask: @escaping Task) {
        _asyns(task: task, mainTask: mainTask)
    }
    
    private static func _asyns(task: @escaping Task, mainTask: Task? = nil) {
        let item = DispatchWorkItem(block: task)
        
        if let main = mainTask {
            item.notify(queue: .main, execute: main)
        }
    }
    
    // 异步延迟
    // 可取消 item.cancel()
    public static func asynsDelay(seconds: Double, task: @escaping Task) -> DispatchWorkItem {
        return _asynsDelay(seconds: seconds, task: task)
    }
    
    // 异步延迟 -> 同步
    // 可取消 item.cancel()
    public static func asynsDelay(seconds: Double, task: @escaping Task, mainTask: @escaping Task) -> DispatchWorkItem {
        return _asynsDelay(seconds: seconds, task: task, mainTask: mainTask)
    }
    
    private static func _asynsDelay(seconds: Double, task: @escaping Task, mainTask: Task? = nil) -> DispatchWorkItem {
        let item: DispatchWorkItem = DispatchWorkItem(block: task)
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + seconds, execute: task)
        
        if let main = mainTask {
            item.notify(queue: .main, execute: main)
        }
        
        return item
    }
    
    
}

使用

Aynscs.asyns(task: {
     // 异步操作
})

Aynscs.asyns(task: {
     // 异步操作
}, mainTask: {
     // 异步完成后进行同步操作
})

思路来源《小码哥教育》

posted @ 2024-08-08 22:23  IT_IOS_MAN  阅读(3)  评论(0编辑  收藏  举报