Created
May 21, 2021 09:25
-
-
Save AlexandrGraschenkov/60d661bdbf224c49f3c8cabfad2a39c5 to your computer and use it in GitHub Desktop.
Helpers for easy control on witch queue run your code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment