Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active January 19, 2019 16:12
Show Gist options
  • Save KentarouKanno/b89bbe0bf4eb0c47af6a4b782cd70291 to your computer and use it in GitHub Desktop.
Save KentarouKanno/b89bbe0bf4eb0c47af6a4b782cd70291 to your computer and use it in GitHub Desktop.

DispatchQueue

import Foundation

extension DispatchQueue {

    class func safeMainThread(execute work: @escaping () -> Void) {
        if Thread.isMainThread {
            work()
        } else {
            DispatchQueue.main.async(execute: work)
        }
    }
    
    class func safeMainThread<T>(execute work: () throws -> T) rethrows -> T {
        if Thread.isMainThread {
            return try work()
        } else {
            return try DispatchQueue.main.sync(execute: work)
        }
    }
}

extension DispatchQueue {

    class func asyncAfter(interval: TimeInterval, work: @escaping () -> Void) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + interval) {
            if Thread.isMainThread {
                work()
            } else {
                DispatchQueue.main.sync(execute: work)
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment