Skip to content

Instantly share code, notes, and snippets.

@AlexandrGraschenkov
Created May 21, 2021 09:25
Show Gist options
  • Select an option

  • Save AlexandrGraschenkov/60d661bdbf224c49f3c8cabfad2a39c5 to your computer and use it in GitHub Desktop.

Select an option

Save AlexandrGraschenkov/60d661bdbf224c49f3c8cabfad2a39c5 to your computer and use it in GitHub Desktop.

Revisions

  1. AlexandrGraschenkov created this gist May 21, 2021.
    43 changes: 43 additions & 0 deletions DispatchQueue+Ex.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@

    extension DispatchQueue {
    static var background: DispatchQueue { return DispatchQueue.global(qos: .background) }
    }

    public typealias Cancelable = ()->()


    func performInMain(mode: CFRunLoopMode = CFRunLoopMode.commonModes, closure: @escaping ()->()) {
    if Thread.isMainThread && mode == .commonModes {
    closure()
    } else {
    CFRunLoopPerformBlock(CFRunLoopGetMain(), mode.rawValue, closure)
    }
    }

    func performInBackground(closure: @escaping ()->()) {
    if Thread.isMainThread {
    DispatchQueue.global(qos: .background).async(execute: closure)
    } else {
    closure()
    }
    }

    func delay(_ delay: Double,
    queue: DispatchQueue = DispatchQueue.main,
    closure:@escaping ()->()) {
    queue.asyncAfter(deadline: .now() + delay, execute: closure)
    }

    fileprivate var _privateKeys = Set<String>()
    func once(file: String = #file, line: Int = #line, col: Int = #column, _ code: ()->()) {
    let key = "\(file)|\(line)|\(col)"

    objc_sync_enter(DispatchQueue.main);
    defer { objc_sync_exit(DispatchQueue.main) }

    if _privateKeys.contains(key) {
    return
    }
    _privateKeys.insert(key)
    code()
    }